Search code examples
javascriptreactjsreact-bootstrap

Can't import a variable inside a string in React.js


This is my code where I try to link some images from a folder

{teamLinks &&
            teamLinks.map(({ title, caption, imgNo }, index) => (
              <div className="col-lg-4">
                <div className="team-member">
                  <img
                    className="mx-auto rounded-circle"
                    src={require(`../assets/img/team/` + { imgNo } + `.jpg`)}
                    alt="logo"

and I get this error

×

    Error: Cannot find module './[object Object].jpg'
    ▶ 2 stack frames were collapsed.
    (anonymous function)
    C:/Users/........./Team.jsx:20



 17 | <div className="team-member">
  18 |   <img
  19 |     className="mx-auto rounded-circle"
> 20 |     src={require(`../assets/img/team/` + { imgNo } + `.jpg`)}
     | ^  21 |     alt="logo"
  22 |   />
  23 |   <h4>{title}</h4>

need some help please...


Solution

  • You can use one of the two approaches here. Do not end up mixing up both

    1. ../assets/img/team/+imgNo+ .jpg
    2. ../assets/img/team/${imgNo}.jpg