4

I was trying to connect my react app to a Mongodb database but this happened.

//index.js
ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);
Robera Negussie
  • 83
  • 1
  • 2
  • 11
  • 2
    This is the first topic on the "[migrating to react 18](https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html)" guide. – Daniel Beck Apr 01 '22 at 17:22

2 Answers2

11

In React 18, is needed to:

import { createRoot } from 'react-dom/client';

creates your root container with this function:

const root = createRoot(document.getElementById("root"));

and then render your root app:

root.render(<YourApp />);

you can read this in: https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html

  • 3
    If using TS, add `!` after the root element reference. – askepott Jun 01 '22 at 13:59
  • 1
    If using TS, add ! after the root element reference to tell typescript *it's never going to be null*. – DarkTrick Jun 13 '22 at 05:31
  • This should be the accepted answer, just my 2 cents. – MadHatter Sep 21 '22 at 02:53
  • 1
    This solution worked for React JS 18 with Laravel & InertiaJs. I researched a lot and finally this solution worked. Thanks a lot. – Jaydeep Goswami Nov 13 '22 at 10:54
  • 1
    I modified app.jsx to this one >> resources\js\app.jsx >> createInertiaApp({ title: (title) => appName, resolve: name => { const page = import(`./Pages/${name}.jsx`) page.layout = page.layout || Layout return page }, setup({ el, App, props }) { // return render(, el); const root = createRoot(el); return root.render(); }, }); – Jaydeep Goswami Nov 13 '22 at 10:55
4

Just replace your code with below in index.js file:

import ReactDOM from "react-dom/client";

const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<App />);
Abhishek Jadav
  • 210
  • 1
  • 5
  • What is the `"root"` meaning ? There's no real `Id` called `"root"`, In React Native I tried to add `` and changed `const root = createRoot(document.getElementById('demo'));` but that didn't work. – Elassoa Oct 09 '22 at 12:00