React Router Dom (v6) with Params
2 min readJun 30, 2022
- Link
- useNavigator
- Router
Link
Let’s take a very simple example to make:
// file 1 - send
import { Link } from 'react-router-dom';<Link
to={'/path/name'}
state={
{
id: '777',
type: 'document',
}
}
>
Go to
</Link>
Then, you can access the state data in ‘/path/name’’ via the useLocation
hook:
// file 2- get
import { useLocation } from 'react-router-dom';const { state } = useLocation();// {
// id: '777',
// type: 'document',
// }
useNavigator
Very similar
// file 1 - send
import { navigate } from 'react-router-dom';const navigate = useNavigate();function goTo() {
navigate('/path/name', { state: { id: 777, type: 'doc } });
}
To get values same example file 2 above
Router
// file 1 and 2
// path: /users/{number}
import * as React from 'react';
import { Routes, Route, useParams } from 'react-router-dom';
function ProfilePage() {
// Get the userId param from the URL.
let { userId } = useParams();
// ...
return (<h1> {userId} </h1>);
}
function App() {
return (
<Routes>
<Route path="users">
<Route path=":userId" element={<ProfilePage />} />
<Route path="me" element={...} />
</Route>
</Routes>
);
}
History
That you may use to navigate
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}