Home > database >  react components not rendering with routes
react components not rendering with routes

Time:06-21

I am using the latest version of react router. When I am using routes in my component, They are not rendering anything but When I remove the routes and use simply the component they are working fine. Not able to understand what is going wrong

This do not work and is not rendering anything on "/" or http://localhost:3000/

import React from "react";
import { BrowserRouter as Router, Route, Navigate } from "react-router-dom";
import Users from "./user/pages/Users";

function App() {
  return (
    <Router>
      <Route path="/" exact>
        <Users />
      </Route>
      <Navigate to="/" />
    </Router>
  );
}

export default App;

This is rendering and working fine.

import React from "react";
import { BrowserRouter as Router, Route, Navigate } from "react-router-dom";
import Users from "./user/pages/Users";

function App() {
  return <Users />;
}

export default App;

CodePudding user response:

import React, {useState} from "react";
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import Users from "./user/pages/Users";
import Profiles from "./Profiles" // this is dummy

function App() {
  const [state, setState] = useState(false)
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Users />}/>
        <Route path="/profiles" element={state ? <Profiles /> : <Navigate to="/" />} /> 
        {/* so you redirect only if your state is false */}
      </Routes>
    </Router>
  );
}

export default App;

CodePudding user response:

It is because, You din't provide which element to render in Route. It has to be mentioned like element={<Users />}. So try like below,

import React from "react";
import { BrowserRouter as Router, Route, Routes, Navigate } from "react-router-dom";
import Users from "./user/pages/Users";

function App() {
  return (
    <Router>
     <Routes>
      <Route path="/" element={<Users />} />
      <Navigate to="/" />
     </Routes>
    </Router>
  );
}

export default App;

CodePudding user response:

Based on the docs, all Route components should be placed inside a Routes component, which is nested inside the BrowserRouter.

Also, I noticed you use Navigate everytime, even when you are already at the index path. I think this may cause a problem...

So, with that in mind, Change your code to

import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Users from "./user/pages/Users";

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/">
          <Route index element={<Users />} />
        </Route>
      </Routes>
    </Router>
  );
}

export default App;
  • Related