React - append-only behavior with createPortal or appendChild?

922 Views Asked by At

I have a large number of elements being rendered by a common parent. When the user takes an action, a few of the elements should be removed, and a few additional elements should be appended. Doing this the 'React way,' the parent has an array that owns the state of all the children elements. On user on click, the parent immutably modifies the array and voila...new elements in the DOM. The problem is that it's often sluggish due to having to compare every element on the page, even with element keys and memoization. I have been fighting with React's diffing algorithm to make this work efficiently. Ideally, this parent component would be responsible solely for appending new children...once they're bootstrapped, they would control their own state.

I've just read about Portals, and am trying to understand whether ReactDOM. createPortal(<Child />, document.getElementById('myFavoriteDiv')) will allow this append-only behavior without altering any of the previously-rendered children. The non-declarative way of doing this I think would be appendChild, but I think that's frowned upon. If this doesn't work like that, what alternatives would you suggest?

1

There are 1 best solutions below

0
On

Try this and see if it works:

ReactDOM.createPortal(<Child />, document.getElementById('myFavoriteDiv')!)