0

I have a question about allocating images dynamically.

I tried to show each images by each cases(depending each data's type and totalCount).

But this code is not working.

export default function Title() {
    let image =
  "../../../assets/images/situations/situation_" + totalCount + ".png";
    return (
        <>
        {types[totalCount - 1] === "situation" ? 
        <SituationTitleStyled img={image}>
        ...
        </SituationTitleStyled>
       }
       </>
    )
}

const SituationTitleStyled = styled.div`
    ...
    background: url(${(props) => props.image});
`;

Otherwise, if the variable "image" is absolute path like "https://mdn.mozillademos.org/files/7693/catfront.png", then it works.

I don't know how i can this work and what is the diffence between using absolute path and relative path. :0

gigibean
  • 5
  • 4

1 Answers1

0

A path should be generated by webpack:

You can import a file right in a JavaScript module. This tells webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the src attribute of an image or the href of a link to a PDF.

So in your code you can just call require:

let image = require("../../../assets/images/..." + totalCount + ".png");

See almost duplicated question.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118