How can I fix ReactDOM.unmountComponentAtNode error in React?

2.7k views Asked by At

The ReactDOM.unmountComponentAtNode(document.getElementById("root")); are unavailable in latest React.

It shows the errors below. How can I fix it?

"You are calling ReactDOM.unmountComponentAtNode() on a container that was previously passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?"

"unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. Instead, have the parent component update its state and rerender in order to remove this component."

import {createRoot} from "react-dom/client";
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App tab={"home"} />);
root.unmount();
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import React from "react";

class LifeCycle extends React.Component {

    state = {opacity: 1};

    disappear = () => {
        root.unmount(document.getElementById("root"));
    }

    componentDidMount() {
        this.timer = setInterval(() => {
            let {opacity} = this.state;
            opacity-=0.1
            if (opacity <= 0) opacity = 1;
            this.setState({opacity});
        }, 200);
    }

    componentWillUnmount() {
        clearInterval(this.timer)
    }

    render() {
        return (
            <div>
                <h1 style={{opacity: this.state.opacity}}>React is too difficult!</h1>
                <button onClick={this.disappear}>click to remove</button>
            </div>
        )
    }
}


export default LifeCycle;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

0

There are 0 answers