Routing
Basic Routing
npm i react-router-dom
import { BrowserRouter } from "react-router-dom";
- In render method wrap App component inside the
BrowserRouter
<BrowserRouter>
<App />
</BrowserRouter>
- In App component, add links and routes
import { Routes, Route, Link } from "react-router-dom";
<Link to="/home">Home</Link>
<Link to="/users">Users</Link>
<Routes>
<Route path="home" element={<Home />} />
<Route path="about" element={<About />} />
<Route path="contact" element={<Contact />} />
</Routes>
Layouts
- Layout Routing with index and no-match route
- Create Layout with
Outlet
Layout.js
<Outlet />
<Routes>
<Route element={<Layout />}>
<Route index element={<Home />} />
<Route path="home" element={<Home />} />
<Route path="users" element={<Users />} />
<Route path="*" element={<NoMatch />} />
</Route>
</Routes>
Active Link
- Change
Link
to NavLink
and add style
const style = ({ isActive }) => ({
fontWeight: isActive ? 'bold' : 'normal',
});
<NavLink to="/home" style={style}>Home</NavLink>
<NavLink to="/users" style={style}>Users</NavLink>
Nested Routes
- Add
Outlet
for nested route
<ul>
<li>
<Link to="/admin">Dashboard</Link>
</li>
<li>
<Link to="/admin/Report">Report</Link>
</li>
</ul>
<Outlet />
<Route path="admin" element={<Admin />}>
<Route index element={<Dashboard />} />
<Route path="report" element={<Report />} />
</Route>
Passing Params
<Route path="users" element={<Users users={users} />}>
<Route path=":userId" element={<User />} />
</Route>
const { userId } = useParams();
Passing Query String or Search Params
const [searchParams, setSearchParams] = useSearchParams();
- Use
get()
method on searchParams
to read the current search params from the URL
const searchTerm = searchParams.get('name') || '';
Programmatic Navigation
- Import
useNavigate
function and call to get navigate function
const navigate = useNavigate();
navigate('/users');