How to import image (.svg, .png ) in a React Component

How to Import Image (.svg, .png) in a React Component

When working with React components, it’s common to import and use images such as .svg or .png files. In this blog post, we will explore different ways to import and use images in a React component.

1. Using the require() function

One way to import an image in a React component is by using the require() function. This method is commonly used for importing static assets, including images.

Here’s an example of how to import an image using the require() function:

import React from 'react';
import image from './path/to/image.svg';

const MyComponent = () => {
  return (
    
My Image
); }; export default MyComponent;

In the above code snippet, we import the image using the require() function and then use it in the src attribute of the img tag.

2. Using the import statement

Another way to import an image in a React component is by using the import statement. This method is commonly used for importing modules, but it can also be used to import images.

Here’s an example of how to import an image using the import statement:

import React from 'react';
import image from './path/to/image.svg';

const MyComponent = () => {
  return (
    
My Image
); }; export default MyComponent;

In the above code snippet, we import the image using the import statement and then use it directly in the src attribute of the img tag.

3. Using the public folder

React also provides a way to import images from the public folder. This method is useful when you have a large number of images or when you want to keep your image files separate from your source code.

Here’s an example of how to import an image from the public folder:

import React from 'react';

const MyComponent = () => {
  return (
    
My Image
); }; export default MyComponent;

In the above code snippet, we directly specify the path to the image file in the src attribute of the img tag, starting from the public folder.

Remember to place your image files in the public folder and update the path accordingly.

These are the three common ways to import and use images in a React component. Choose the method that best suits your project’s requirements and file structure.

Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *