Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add inline src to image ( Webpack 5 )

I tried to add a string representation of [src] to an image, but it doesn’t work.

import React from "react";
import cn from "classnames";
import "./index.scss";

export const PanelItem = (props) => {
  return (
    <li className={cn("panel-item", props.className)}>
      <a href={props.linkData.url}>
        <img src="./image.png" alt={props.iconData.alt} />
        <span>{props.linkData.text}</span>
      </a>
    </li>
  );
};

Using import statement works well always.

import React from "react";
import cn from "classnames";
import "./index.scss";
import image from "Icons/image.png";

export const PanelItem = (props) => {
  return (
    <li className={cn("panel-item", props.className)}>
      <a href={props.linkData.url}>
        <img src={image} alt={props.iconData.alt} />
        <span>{props.linkData.text}</span>
      </a>
    </li>
  );
};

How to make it possible ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the webpack context and define a component like below and use that component instead. It is a sample component for SVGs
import React from ‘react’

export default function Img (props) {
  const svgContext = require.context(
    '../resources/svgs',
    true,
    /.*\.svg$/,
  )

  return <img src={svgContext(`./${props.fileName}.svg`)} alt={props.altText} className={props.className} />
}

You can use that component

<Img fileName={'sample'} className="iconDropDown" />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading