Home > Software engineering >  Function component on the same page in not picking in route (react-router-dom v6) of react project
Function component on the same page in not picking in route (react-router-dom v6) of react project

Time:12-26

I have created a route in my react project using the methods of react-router-dom version 6.2.1.

But when I tried to fetch one route of a functional component written on the same implementation component it is not working.

App.js

import React from 'react';
import './App.css';
import {Routes ,Route} from 'react-router-dom';
import HomePage from './pages/homepage/homepage.component';

const CarsPage= () => {
  <div>
    <h1>CARS PAGE</h1>
  </div>
}

function App() {
  return (
   <div>
     <Routes >
       <Route exact path='/' element={<HomePage />} />
       <Route exact path='/cars' element={<CarsPage/>} /> // This route is not working.
     </Routes>
   </div>
  );
}

export default App;

Issue

The hats route is not picking up.

CodePudding user response:

Your forgot the return statement in CarsPage

Change it to:

const CarsPage= () => {
  return (
  <div>
    <h1>CARS PAGE</h1>
  </div>
)
}

CodePudding user response:

You need to wrap the components in BrowserRouter. See everything works here: https://codesandbox.io/s/festive-leavitt-7tr1d?file=/src/App.js

CodePudding user response:

Looking at the above implementation, the CarsPage component does not return anything. Refactor it to return your JSX like so.

const CarsPage = () => (
    <div>
      <h1>CARS PAGE</h1>
    </div>
);

Also, import BrowserRouter from "react-router-dom" and wrap the "react-router-dom" component <Routes /> with BrowserRouter as seen in the docs like so

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

...

function App() {
  return (
    <div>
      <Router>
        <Routes>
          <Route exact path="/" element={<HomePage />} />
          <Route exact path="/cars" element={<CarsPage />} />
        </Routes>
      </Router>
    </div>
  );
}

  • Related