rrrrTTTyyy
rrrrTTTyyy

Reputation: 59

Navigation in react

I am trying to implement something that when the user clicks a button a the user will redirect to add page. I have tried this using Navigate. But I am getting this error. Uncaught Error: <Navigate> may be used only in the context of a <Router> component. Here is the code that I tried.

Home.js

const[gotoAdd, setAdd] = React.useState(false);

  if(gotoAdd){
    return <Navigate to="/Add"/>
  }

<Button color="inherit" onClick={()=>{
          setAdd(true);
        }}>Add Employee</Button>

Add.js

import React from 'react'

export const Add = () => {
  return (
    <div>Addd</div>
  )
}
export default Add;

Upvotes: 3

Views: 69

Answers (1)

Tim Dang
Tim Dang

Reputation: 29

First, make sure that you must install react-router-dom and add it to your app

index.js

import ReactDOM from 'react-dom'
import App from './App'
import { BrowserRouter } from 'react-router-dom'

const rootElement = document.getElementById('root')
ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  rootElement
)

in App component

import { Routes, Route } from 'react-router-dom'

export default function App() {
  return (
    <Routes>
      <Route path='/' element={<Home/>} />
      <Route path='/abc' element={<Abc/>} />
      <Route path='/def' element={<Def/>} />
      <Route path='/xyz' element={<Xyz/>} />
    </Routes>
  )
}

After that, you will use useNavigate to navigate

useNavigate()

import { useNavigate } from "react-router-dom";

export default function Component() {
  let navigate = useNavigate();
  navigate("/add"); 
}

Upvotes: 2

Related Questions