Home > Net >  I am not able to use the router in react js
I am not able to use the router in react js

Time:06-12

I have been trying to use a router on react project but getting an error :

A Route is only ever to be used as the child of Routes element, never rendered directly. Please wrap your Route in a Routes.

The Code Is Shown Below

import About from "./container/About";
import Profile from "./container/Profile";
import { useState } from "react";
import {BrowserRouter as Routes,Route} from 'react-router-dom'
function App(){
  const [state, setState] = useState('')
  return(
    <div className="App">
      <button onClick={()=>setState('about')}>About</button>
      <button onClick={()=>setState('profile')}>Profile</button>
      <Routes>
        <Route component={About} path='/about'></Route>
      </Routes>
    </div>
  )
}
export default App;

CodePudding user response:

If you're on version 6 of react-router-dom, you need to name the props differently:

<Route element={About} path='/about'></Route>

In version 5, it was named component.

I assume you're on version 6, because I can't remember version 5 having the Routes component. Also, you need to import the components differently, and wrap everything with the BrowserRouter.

import About from "./container/About";
import Profile from "./container/Profile";
import { useState } from "react";
import {BrowserRouter, Routes, Route} from 'react-router-dom'
function App(){
  const [state, setState] = useState('')
  return(
    <BrowserRouter>
      <div className="App">
        <button onClick={()=>setState('about')}>About</button>
        <button onClick={()=>setState('profile')}>Profile</button>
        <Routes>
          <Route element={<About />} path='/about'></Route>
        </Routes>
      </div>
    </BrowserRouter>
  )
}
export default App;

CodePudding user response:

I'm not sure you can call the BrowserRouter component the way you did in your code. Perhaps if you wrap your code in the router - in a way that it's the topmost parent, such as this example and render your buttons inside of it then it should work fine.

CodePudding user response:

Put the path before the component

    <Route path='/about' element={About}></Route>

Also ,

Wrap your in the index.js file with BrowserRouter

<BrowserRouter>
<App/>
</BrowserRouter>
  • Related