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

When I use React Images won't display when i store the URL in an object

I have just started working with react recently but I have been running into an issue with the project that I am working on where I’m trying to display a list of icons with links.

when storing the src for each icon in the list below it stops the entire page from rendering, and logs an error that it can’t find the image. If I paste the scr directly into the code there is no error when loading the images, but for reusability and readability, I thought it would be best practice to map a list into HTML components instead.

import SideLinksCss from './sideLinks.module.css';
export default function SideLinks() {
    const links = [
        {
            name: "linkedin",
            url: "",
            src: "../assets/linkedin-icon.png"
        },
        {
            name: "github",
            url: "",
            src: "../assets/github-icon.png"
        },
    ]
    return (
        <div className="side-links">
            <ul>
                {links.map(link => 
                    <li>
                        <a>
                            <img src={link.src} alt={link.name} />
                        </a>
                    </li>
                    )}
            </ul>
        </div>
    );
}

if there is something dumb I’m missing id love to hear since I’m new to react, or if there is a better way to do it.

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 do not need to import or require the images. Just put them in the public folder and they will be available. Then you can do:


function App() {
  const links = [
    {
      alt: "fig1",
      src: "./0001.jpg",
    },
    {
      alt: "fig2",
      src: "./0002.jpg",
    },
  ];
  return (
    <div className="App">
      <ul>
        {links.map((link) => (
          <li key={link.alt}>
            <a>
              <img src={link.src} alt={link.alt} />
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

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