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.
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.
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);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
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.