Search code examples
javascriptreactjswebreact-props

How to add image through props in React JS


I'm trying to create reusable card component and I don't know how to add the image through the props, I would appreciate your help. Now I'm using {require("../assets/wheat.svg")} but it doesn't work.

CardsScreen.js

import React from "react";

import styles from "../styles/card-styles/cards.css";

import Bounce from "react-reveal/Bounce";

const CardsScreen = () => {
  function Card(props) {
    return (
      <div className="card-content">
        <img className="card-image" src={props.view}></img>
        <h6 className="card-header">{props.heading}</h6>
        <p className="card-paragraph">{props.description}</p>
      </div>
    );
  }

  return (
    <div className="cards-container">
      <Bounce bottom>
        <Card
          view={require("../assets/wheat.svg")}
          heading="Heading"
          description="Lorem ipsum dolor sit amet consectetur. Nunc donec ullamcorper viverra lectus quis pretium volutpat eget. Aliquam ultrices tincidunt nulla commodo."
        />
      </Bounce>
    </div>
  );
};

export default CardsScreen;


Solution

  • If we are looking to add the static image, then we can import it and pass it with the view as prop.

    import blurImage from './images/part-blurry-image.jpg';
    function Card(props) {
        return (
          <div className="card-content">
            <img className="card-image" src={props.view}></img>
            <h6 className="card-header">{props.heading}</h6>
            <p className="card-paragraph">{props.description}</p>
          </div>
        );
      }
    export default function CardScreen() {
      
    
      return (
        <div className="cards-container">
          <Card
            view={blurImage}
            heading="Heading"
            description="Lorem ipsum dolor sit amet consectetur. Nunc donec ullamcorper viverra lectus quis pretium volutpat eget. Aliquam ultrices tincidunt nulla commodo."
          />
        </div>
      );
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>