reactjsreact-portal

Can I port an element to any DOM node using react portals?


I want to loop over a bunch of custom elements and give them parent to child relationship. So arr[0] will be child of arr[1], which will be the child of arr[2] ...

The following method adds <WrapperDraggable/> elements to the boxes array.

addElement=(count,zIdx) => {
    var newDom = <WrapperDraggable count={count} id={"portal"+count.toString()}
                  zIdx={zIdx} width={count*175} height={count*175}/>
    this.setState({boxes:this.state.boxes.concat(newDom)})
}

I thought of using portals to port boxes[0] to boxes[1]'s id and so on. So for boxes length 2, I want to make a DOM structure like,

<div id="portal3"/>
    <WrapperDraggable id="portal2"/>
        <WrapperDraggable id="portal1"/>

However, when I am trying to use react portals to render a div and attach it to another div with id "portal",

<div id={"portal"+(this.state.boxes.length)}>
{this.state.boxes.map((box,index)=>{
    {ReactDOM.createPortal(box, document.getElementById("portal"+(this.state.boxes.length-index).toString()))}
})}

For simplicity imagine the boxes array is already in reverse order.

I don't get any attached to the outermost portal div. The console also doesn't give me any error messages.

Am I doing something wrong? If so, how can I implement a similar behavior in my code?

Thanks in advance.


Solution

  • The issue seems to be in the map function. You are not returning anything from the function.

    Return properly and it should work fine.

    {this.state.boxes.map((box,index)=>{
        return ReactDOM.createPortal(  //Return here
            box,
            document.getElementById("portal"+(this.state.boxes.length-index).toString())
        )
    )}
    

    Hope it helps. Revert for any doubts/clarifications.