ReactDOM.render is no longer supported in React 18

  • react-js
  • 67 Views
  • 1 Min Read
  • 8 Jul 2024

Hi coder Welcome to this solution, React 18 has changed how developers display content on screens. A big change is removing ReactDOM.render(). This has confused many developers. So, in this article, we will explain to you how we can fix it.

 

Before we learn the solution, let us know about this error. We have given the code below, which is causing the error.

 

 

Error Code

 
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById('root')
);

 

 

Solving the Error

 

When encountering this error, consider using createRoot() instead of render(). Also, import ReactDOM from react-dom/client rather than react-dom. The method has been updated to createRoot() exported from react-dom/client.

 

After changing your code, the index.js file should look like this:

 
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

ReactDOM.createRoot(document.getElementById('root'))
    .render(
        <React.StrictMode>
            <App />
        </React.StrictMode>
    );
 

You should make these two changes, which have to be changed in the React 18 version.

 

Replace:

 
import ReactDOM from 'react-dom';
ReactDOM.render(<React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root'))
 

To:

 

import ReactDOM from 'react-dom/client';
ReactDOM.createRoot(document.getElementById('root')).render(<React.StrictMode><App /></React.StrictMode>);
 
 

Reasons Behind This Error

 

In React 18, there's a change: ReactDOM.render() is no longer supported. Instead, developers should use ReactDOM.createRoot() to render components into the DOM. This change makes rendering more efficient and supports concurrent mode and rendering better in React apps.

 

 

Conclusion

 

Many updates are coming to React very often, due to which we need to stay updated. All updates bring something new to make the way we work easier.

 

If you have any questions about this solution or any other error related to web development, you can ask them in the question box given below, and you will get an answer soon.

Didn't find your answer? Add your question.

Share

Comments (0)

No comments yet. Be the first to comment!