Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render multiple React components into a single DOM element

I'm looking to render multiple modals into a single ReactDOM element. Here's the HTML structure that React renders to.

<body>
    <div id="modal-socket"></div> // Insert multiple here
    <div id="wrapper">
        // Other content goes here
    </div>
</body>

There's a long story behind why I need to render multiple components into #modal-socket but I want to do something akin to this:

ReactDOM.render(<AddMeasurableModal />, document.getElementById("modal-socket"));
ReactDOM.render(<AddMeasurableModal />, document.getElementById("modal-socket"));
ReactDOM.render(<AddMeasurableModal />, document.getElementById("modal-socket"));

Obviously this replaces the current content of #modal-socket on each render call.. So I don't get my end result. Boo.

Did a search and found a few answers on it but none meet my needs.

Cheers.

like image 685
Dezachu Avatar asked Dec 10 '22 16:12

Dezachu


2 Answers

As you told in a comment, the dynamic way would be something like this Inside of a main component you could do:

Imagine having an array like:

let myArray = [
  {
     prop1: 'hello world'
  },
  {
     prop1: 'Hey there!'
  }
]

//Then in the render function (you can put that array into the state or something)
render(){
      return (
         <div>
           {myArray.map((entry,index) => {
              return <AddMeasurableModal key={index} {...entry} />
           })}
         </div>
      )
}

this will create as many AddMeasurableModal components as there are entrys in the myArray variable and add every property stored as props onto the component (In this case, every AddMeasurableModal component has access to the this.props.prop1 value, because of the {...entry} spread syntax)

Notice how I only put myArray.map() into the render function inside of {}? React renders every array of components without further configuration inside of the render function. And Array.map() returns an array. Just make sure to return only valid react elements! When doing this, don't forget to add a uniqe key prop to each element to avoid warnings.

EDIT: in this case, the key prop is the current index in the array, but when fetching data from a server I would recommend to use a uniqe id from the database or something to avoid rendering bugs. If you don't want to map over an array, you can just set a number of components and then loop over them, creating an array of components and put them into the render function.

like image 74
Joschua Schneider Avatar answered Mar 08 '23 04:03

Joschua Schneider


Wrap your multiple modals into 1 container and render that, eg:

let modals = (
  <div>
    <AddMeasurableModal />
    <AddMeasurableModal />
    <AddMeasurableModal />
  </div>
);

ReactDOM.render(modals, document.getElementById("modal-socket"));
like image 36
luanped Avatar answered Mar 08 '23 03:03

luanped