0

I am creating a simple React component that displays images in a list/array.

The source is shown below:

import React from "react";
import styled from "styled-components";
import burgerTop from "../../assets/images/burgerTop.png";
import burgerBottom from "../../assets/images/burgerBottom.png";

const BurgerComponent = props => {
  console.log(JSON.stringify(props));
  const BurgerDiv = styled.div`
    width: 500px;
    margin: 0 auto;
    text-align: center;
    display: flex;
    flex-direction: column;
  `;
  return (
    <BurgerDiv>
      {props.burger.map(burgerItem => {
        console.log(burgerItem);
        const imgSrc = burgerItem.img;
        console.log(imgSrc);
        return <img key={burgerItem.id} src={imgSrc} />;
      })}
    </BurgerDiv>
  );
};

export default BurgerComponent;

Props are shown as below

{
  "burger":[
    {
      "type":"top",
      "img":"burgerTop",
      "value":1,
      "id":"sss2",
      "addable":false
    },
    {
      "type":"bottom",
      "img":"burgerBottom",
      "value":1,
      "id":"aaa7",
      "addable":false
    }
  ]
}

But the image path is not taken from import.

Not sure what I am doing wrong.

Please help.

1 Answer 1

1

img's source property should be a URL, or base64 string. Your burger prop doesn't have a source property like that.

I noticed that you are importing burgerTop and burgerBottom from assets folder. Maybe you can use those images like this:

{props.burger.map(burgerItem => {
        const imgSrc = burgerItem.img === "burgerTop" ? burgerTop : burgerBottom ;
        return <img key={burgerItem.id} src={imgSrc} />;
      })}
Sign up to request clarification or add additional context in comments.

2 Comments

But array will have few more images, and i will add it on top, than how will this solution work.
Try storing images' URLs in your prop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.