I have written several articles about react 18 and its new features, APIs and the bugs from breaking changes. Take a look at these articles if they match the error which you might be trying to fix.

Solved - ReactDOM.render is no longer supported in React 18. Use createRoot instead.
“ReactDOM.render” method which is by default used in create-react-app or other template files is deprecated in React 18. Check out the new implementation of the index.js file.
Solved - createRoot() Target container is not a DOM element
This error occurs commonly due to either passing in the wrong “id” to the “document.getElelementById()” method or by calling the React script before the div tag with “id” in the “index.html” file.

TypeScript is a powerful tool and we all can agree on that. But with more power comes, more responsibilities. So how should the boilerplate code for a React 18 project's index.ts file look like written in TypeScript?

If you are only interested in the JavaScript version of the React 18 index.js file, check out the following article instead.

React 18 - How to write the root index.js using JavaScript
The boilerplate code for the root index.js file in React 18 project,

The index.ts

import React from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

const rootElement = document.getElementById("root");
if (!rootElement) throw new Error('Failed to find the root element');
const root = createRoot(rootElement);
    <App />


What changed? The above code includes the new createRoot method that was introduced in React 18. This is now the default method to define a React project.

What's the difference between TypeScript's version from JavaScript's version of the index file. The only difference is the inclusion of the following code.

if (!rootElement) throw new Error('Failed to find the root element');

This is basically TypeScript saying the "rootElement" constant could be null and could throw an error. Therefor we wrote an additional step to catch that error. Otherwise, we would be getting the following error.

type error