How to render an element in React which was created by createElement()?

Viewed 293

I have created an image element by using:

const image = document.createElement('image'); // or new Image();

How can I render this image variable in React ?

I don't want to use Html tags to do something like this:

<img src={image.src} ... />

Is there any other way ?

2 Answers

Well either create a <div class="parent"> </div> and then use

document.querySelector(".parent").appendChild(imageElement)

or simply,

document.appendChild(imageElement)

This is the wrong way to go about doing this. You shouldn't directly manipulate the DOM with React. I would instead have an array of objects in your state, and in your component, map the objects to the elements of your choosing. Like this

const Component = () => {
    const [components, setComponents] = useState([{src:'path/to/src', alt:'altTag'}])
    return(
      <>
          {
          components.map(e => {
              return(<img src={require(e.src)} alt={e.alt} />)
          })
          }
      </>
      )
}

Wrote this from memory/without testing so there might be something wrong so dont kill me. But if you need to render it anywhere, make it its own component. If it's truly just one image, then you don't need the array/map just use an object and render it same way

Related