skip to Main Content

Full error : Warning: Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.

My code in index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { createRoot } from "react-dom/client";

const container = document.getElementById("root");
const root = createRoot(container);
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App />}></Route>
      </Routes>
    </BrowserRouter>
  </React.StrictMode>
export default root;
);

My code in app.js

import "./App.css";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import Navbar from "./components/Navbar";
import MyHome from "./components/MyHome";
import About from "./components/About";
import root from "./index";

function App() {
  const router = createBrowserRouter([
    {
      path: "/",
      element: (
        <div>
          <Navbar></Navbar>
          <MyHome></MyHome>
        </div>
      ),
    },
    {
      path: "/about",
      element: (
        <div>
          <Navbar></Navbar>
          <About></About>
        </div>
      ),
    },
  ]);

  root.render(<RouterProvider router={router}></RouterProvider>);
}

export default App;

I was trying to setup my react router but got this error. I looked through the documentation of react router dom but thats pretty confusing and couldnt find my solution

2

Answers


  1. root.render should only be called once. You call it once in App, and once in index. It should really only be called in index.js. App should be a standalone component which does not attempt to re-render the root element. The startup docs for react-router are pretty useful to get started using it:

    https://reactrouter.com/en/main/start/tutorial

    Login or Signup to reply.
  2. First you have used root.render() twice, use it only in index.js
    Secondly you have defined your routes in index.js and then tried to create nested routes.
    You dont need to write your code like this

    root.render(
      <React.StrictMode>
        <BrowserRouter>
          <Routes>
            <Route path="/" element={<App />}></Route>
          </Routes>
        </BrowserRouter>
      </React.StrictMode>
    

    instead you should have done it like this

    root.render(
      <React.StrictMode>
        <BrowserRouter>
        <App/>
        </BrowserRouter>
      </React.StrictMode>)
    

    And then define your routes in the App.js as you did.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search