How to pass an image as a prop in react

Passing an Image as a Prop in React

To pass an image as a prop in React, you need to follow these steps:

  1. Import the image file in the component where you want to use it. For example, if you have an image called “example.jpg” in the same directory as your component file, you can import it like this:

    import exampleImage from './example.jpg';
  2. Create an image element in the component’s render method and pass the image file as a prop to it. You can use the imported image variable directly. For example:

    render() {
      return (
        <div>
          <img src={exampleImage} alt="Example" />
        </div>
      );
    }

That’s it! Now you have successfully passed an image as a prop in React.

Example

Here’s an example that demonstrates how to pass an image as a prop in React:

// ExampleComponent.js

import React from 'react';
import exampleImage from './example.jpg';

export default function ExampleComponent() {
  return (
    <div>
      <img src={exampleImage} alt="Example" />
    </div>
  );
}

// App.js

import React from 'react';
import ExampleComponent from './ExampleComponent';

function App() {
  return (
    <div>
      <h1>My App</h1>
      <p>This is my app.</p>
      <ExampleComponent />
    </div>
  );
}

export default App;

In the above example, we import the “example.jpg” image and use it in the ExampleComponent. Then, we include the ExampleComponent in the App component, which renders the image along with other content.

Leave a comment