Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactDOM.render to insertBefore instead of replace? (with reason for it, CSS adjacent sibling selector)

Tags:

reactjs

Currently with React I am doing this:

 ReactDOM.render(<HelloMessage name="John" />, mountNode);

This replaces the entire contents of mountNode, is it possible to make it insertBefore instead of replace? I want to insert it as first child.

EDIT - why i need this, simplified case. My component is a menu, when it is in the open state, it opens and reveals items like a drawer. So I have to give the element after my menu component a box shadow to show that it is over the revealed elements. I do this with this css:

.myComponent[data-state=open] + div {
  background-color: red;
}

However myComponent has no adjacent siblings, as i replaced the contents of a target elmeent so this fails. So my work around is to, on every render, set the attribute on the parent node:

    if (this.refs.myc) {
        this.state.profiles.length > 0 ? this.refs.myc.parentNode.setAttribute('data-state', 'open') : this.refs.myc.parentNode.removeAttribute('data-state'); // my ugly work around, put the data-state attribute on the parentNode of mountNode
    }

However this is not efficient, as it is not setting on virtual dom, but every time on the dom. So i wanted to insert my component as the first child in the body, this way my stylesheet will work.

Here is the working fiddle with work around - https://jsfiddle.net/Noitidart/69z2wepo/26319/

like image 883
Noitidart Avatar asked Jan 04 '16 09:01

Noitidart


People also ask

Why was ReactDOM moved to a separate library?

The reason React and ReactDOM were split into two libraries was due to the arrival of React Native. React contains functionality utilised in web and mobile apps. ReactDOM functionality is utilised only in web apps.

What does the ReactDOM render () method do?

The ReactDOM.render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.

Why ReactDOM render is not working?

Use createRoot instead" occurs because the ReactDOM. render method has been deprecated. To solve the error, create a root element and use the ReactDOMClient.

Is ReactDOM render necessary?

The render() function is one of the most useful and important functions of ReactDOM. it returns a reference to the component after rendering a React element into the DOM in the provided container (or returns null for stateless components).


1 Answers

Did you solve this? You should definitely be able to mount it in different places

const newChildNode = document.createElement('DIV')
newChildNode.id = 'new-child-node'
document.body.insertBefore(newChildNode, document.getElementById('root'))

ReactDOM.render(<App />, newChildNode)
like image 174
Jonathan Irwin Avatar answered Nov 09 '22 14:11

Jonathan Irwin