Home > database >  Why is my react component not rendering only when using routes? react-router-domV.6
Why is my react component not rendering only when using routes? react-router-domV.6

Time:02-25

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter as Router } from 'react-router-dom';

ReactDOM.render(
  <React.StrictMode>
    <Router>
      <App />
    </Router>
  </React.StrictMode>,
  document.getElementById('root')
);

App.js

import React from 'react';
import { Routes, Route } from "react-router-dom";
import Main from './Pages/Home/Main.js';
import NotFound from './Helpers/NotFound.js';

function App() {
  return (
    <div className="app-routes">
      <Routes>
        <Route path="/">
          <Main />
        </Route>
        <Route>
          <NotFound />
        </Route>
      </Routes>
    </div>
  );
}

export default App;

Main.js

import React from 'react';
import './main.css';

function Main(){
    return (
        <div className="main-content">
            <h1>This is the Main Page</h1>
        </div>
    );
}

export default Main;

Definitely not a component import issue tested without routes and works perfectly but when I add routes or even just route by itself nothing will render. I have react-router-dom v.6 installed

CodePudding user response:

React-router v6 api has changed. you need to use element prop to render a component.

  <Routes>
        <Route path="/" element={<Main>} />
        <Route path="/custom" element={<div>custom</div>} />
        <Route path="*" element={<NotFound />}>
  </Routes>

CodePudding user response:

react-router-dom@6 uses element property in the route to display the component

To display not found page use path ="*" and add it the end of all the routes so whenever routes don't match I goes to the not found (404)page.

 <Routes>
        <Route path="/" element={<Main />}/>
         //all your routes here 
        <Route path="*" element={ <NotFound />}/> //in the last
        
      </Routes>

  • Related