How to put the image address in src without it having to be a Component in React

Asked

Viewed 1,389 times

0

Good evening I have a js file with an array of objects and one of these properties is image as I do to render it in src already tried {item.image} but it’s just a string and React apparently uses images as if they were components, another detail is that the image property of these objects receives a string that is the location of these images .. /Assets/imageTal.png, it does not render at all or searches at least

2 answers

0

Here is a very generic example, but it shows that yes, it is possible without.

function carregarImagem() {
  var imagem = document.getElementById("imagem");
  imagem.src = "https://s2.glbimg.com/RV6Buc-U84d00Ky_aBhOiGWZeXs=/0x59:2000x1185/540x304/smart/http://i.s3.glbimg.com/v1/AUTH_59edd422c0c84a879bd37670ae4f538a/internal_photos/bs/2019/p/M/8bGAWSRuWFf6NgMwCS1w/bancoimagemfotoaudiencia-ap-408260.jpg";
}
<img id="imagem" src="" title="Clique para carregar" width="450" height="300" onclick="carregarImagem()">

0


Gabriel, in React these local images need to be imported. You can make a require within the component img or your array. See what’s easier. I made a component here very quickly and it worked, see:

return (
    <div className="App">
      {images.map(item => (
        <div key={item.id}>
          <img src={require(`${item.image}`)} alt="imagem" />
        </div>
      ))}
    </div>

my array was like this:

const images = [
  {
    id: Math.random(),
    image: "./assets/article.full.jpg"
  },
  {
    id: Math.random(),
    image: "./assets/blue-flame-2.jpg"
  },
  {
    id: Math.random(),
    image: "./assets/energy-main-6.jpg"
  }
];
  • 1

    Looks like it might work, thanks

  • You can use require in the array or even import the images and put the import type name:import { nome_que_vc_quiser } from './assets/sua_imagem.jpg'; and ai in the Voce array uses the name you placed in the image.

  • po ta not working, look what I wrote

  • <ul> { items.map(item => ( <li key={item.id}> <button onClick=this.handlerClick.bind(this,item)}> <div classname="containerImage"> <img src={require(${item.image})} alt="test"/> </button> </li> ))} ) </ul>

  • Sort your array where the image is. It will be easier to understand.

  • I managed to settle the way you said thanks so I marked it as settled!

  • Show! Anything calls there.

  • Of course! Thank you

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.