'React Image Rendering using require()

I'm trying to render images in react using require(). Below is a snapshot of the code that is working.

const ProjectBlock: React.FC<{ data: PROJECTBLOCK }> = (props) => {
  const baseUrl = "../../../assets/images/forkify.png";
  return (
    <div className="projectblock">
      <div className="projectblock__heading">
        <h3 className="subheading-default margin-bottom">{props.data.heading}</h3>
        <p className="para">{props.data.content}</p>
        <h4 className="smallheadin">{props.data.technologies.join(" · ")}</h4>
      </div>
      <img
        src={require("../../../assets/images/forkify.png")}
        alt=""
        className="projectblock__image"
      />
    </div>
  );
};

In the above case, I'm passing a string to the require() function. However when I try and store the string in the baseUrl variable and pass it to the require() function, it does not work and gives the following error in the console.

Uncaught Error: Cannot find module '../../../assets/images/forkify.png'

Here is how I am trying to use the variable with require()

const ProjectBlock: React.FC<{ data: PROJECTBLOCK }> = (props) => {
  const baseUrl = "../../../assets/images/forkify.png";
  return (
    <div className="projectblock">
      <div className="projectblock__heading">
        <h3 className="subheading-default margin-bottom">{props.data.heading}</h3>
        <p className="para">{props.data.content}</p>
        <h4 className="smallheadin">{props.data.technologies.join(" · ")}</h4>
      </div>
      <img src={require(baseUrl)} alt="" className="projectblock__image" />
    </div>
  );
};

Have even tried with template literals. Please help!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source