Ramin Jafary
Ramin Jafary

Reputation: 23

Is there any problem to have many ReactDOM.render() in a ReactJS Project?

We are working on a Laravel project and it is written totally with JavaScript/HTML/JQuery. We are considering migrating to React as Laravel supports it. Is it OK to have many ReactDOM.render() ( per component) in the initial steps so we can progressively and fully convert our code base in the long run?

Is it necessary to access ref or just we can render each component like this:

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

ReactDOM.render(<App/>, document.querySelector("#form"))

and use it like this for every component:

// some html code and then
...
<div id="form"> </div>
<div id="modal"> </div>
<div id="navbar"> </div>
...


// rest of html code

Upvotes: 2

Views: 646

Answers (2)

Sagiv b.g
Sagiv b.g

Reputation: 31024

Yes this is totally fine, when you call ReactDOM.render multiple times it will basically just triggers a diffing, very similar to the render method of a class component.
I actually wrote an article (with a tutorial) about "Integrate React with other applications and frameworks" that talks exactly about that topic.

The bottom line of this approach is that you can expose a global object with mount and unmount functions of your widget / mini-app and inside it call ReactDOM.render or ReactDOM.unmountComponentAtNode.

window.MyComponent = {
    mount: (props, container) => {
        ReactDOM.render(<Component {...props} />, container);
    },
    unmount: (container) => {
        ReactDOM.unmountComponentAtNode(container);
    }
}

Then in another part in the page you can call these functions, no matter what library or framework you are using obviously.

The beauty here, is that other react applications can use it as if it was a real component:

class MyComponentWrapper extends PureComponent {

    // create a ref so we can pass the element to mount and unmount
    myRef = React.createRef();

    componentDidMount() {
        // initial render with props
        window.MyComponent.mount(this.props, this.myRef.current);
    }

    componentDidUpdate(prevProps) {
        if(prevProps !== this.props){
            window.MyComponent.mount(this.props, this.myRef.current);
        }
    }

    componentWillUnmount(){
        window.MyComponent.unmount(this.myRef.current);
    }

    render() {
        return <div ref={this.myRef}></div>
    }
}

Hope it helps.

Upvotes: 1

P Varga
P Varga

Reputation: 20239

Yes, that's completely fine. React is designed for gradual adoption.

Upvotes: 0

Related Questions