Open In App

New DOM Methods in React 18

React 18 has introduced several exciting features and improvements, including new DOM methods that enhance the developer experience. In this article, we will explore these new methods, discuss their syntax, and provide step-by-step instructions on how to integrate them into your React applications.

Prerequisites:

Key Features of React 18:

Steps to Create a React application:

Step 1. Open a folder in cmd and use this command to create a React application, this command will create the React app of the latest version.



npx create-react-app foldername

Step 2. Navigate to the root directory of your project using the following the command.

cd foldername

Project Structure:



The updated dependencies in package.json file will look like:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-bootstrap": "^2.10.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Now you can use new DOM methods.

In React 17, In “index.js” file we used “ReactDOM.render” to create a root to render our application using that root.

Syntax:

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

createRoot:

The “createRoot” method is used to create a new root for a React application. It takes a container element as an argument and returns a root object. You can then use the render method on this root to render your React component into the specified container.

Approach:

import ReactDOM from 'react-dom/client';

Example: Using “createRoot” method to render my React component.




// App.js
import './App.css';
 
function App() {
    return (
        <div className="App">
            <h1 style={{ color: "green" }}>
                Geeks For Geeks
            </h1>
        </div>
    );
}
 
export default App;




import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
 
const container = document.getElementById('root');
 
const root = ReactDOM.createRoot(container);
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);
 
reportWebVitals();

Start your application using the following command.

npm start

Output:


Article Tags :