The React Router is probably the most popular library in the React ecosystem, It has experienced many iterations and major changes, just last month, but also ushered in a large formal updated version 6.x, the latest 6.0.2, compared to previous 5.x version made significant changes, whether from the usage or have obvious ascending from the performance, this article will use the new and old version of the method of contrast can let you to the fastest speed to fit the new usage.
The new version has the following changes compared to the old version.
Route property changesโ
Route
component property has been changed. It removes thecomponent
property andrender
property, and adds aelement
property.
// 5.x
<Route path="/" component={App} />
<Route path="/home" render={() => <Home />} />
// 6.x
<Route path="/" element={App} />
Replace Switch component with Routes component.โ
React router v6 remove the Switch
component, and replace it with Routes
component. The Route
component should be used in the Routes
component, otherwise it will throw an error.
// v5.x
<Switch>
<Route path="/home" component={Home} />
<Route path="/login" component={Login} />
</Switch>
// v6.x
<Routes>
<Route path="/home" element={<Home/>} />
<Route path="/login" element={<Login/>} />
</Routes>
Nested routesโ
This is one of the most powerful features of React Router making it so you don't have to mess around with complicated layout code. The vast majority of your layouts are coupled to segments of the URL and React Router embraces this fully.
function App() {
return (
<Routes>
<Route path="invoices" element={<Invoices />}>
<Route path=":invoiceId" element={<Invoice />} />
<Route path="sent" element={<SentInvoices />} />
</Route>
</Routes>
);
}
This route config defined three route paths:
"/invoices"
"/invoices/sent"
"/invoices/:invoiceId"
You can also use useRoutes
to define the routes.
function App() {
const element = useRoutes([
{
path: "/invoices",
element: <Invoices />,
children: [
{ path: ":/invoiceId", element: <Invoices /> },
{ path: "sent", element: <SentInvoices /> },
],
},
]);
return element;
}
Redirectโ
React router v6 remove the Redirect
component, but you can use Navigate
component to redirect.
<Routes>
<Route path="/home" element={<Home/>} />
<Route path="/" element={<Navigate to="/home"/>}>
</Routes>
Active Linkโ
Jumping to Link
or NavLink
is almost the same as the previous version, the only difference is that the NavLink
component is highlighted (highlighted using the style or className callback function, as follows).
// v5็ๆฌ
<NavLink to="/home" activeStyle={{color:'#f00'}}>Home</NavLink>
<NavLink to="/home" activeClassName="active">Home</NavLink>
// v6็ๆฌ
<NavLink to="/home" style={({isActive})=>(isActive ? { color: '#f00' } : {})}>Home</NavLink>
<NavLink to="/home" className={({isActive})=> isActive ? 'current' : ''}>Home</NavLink>
useNavigate()โ
React-Router v6 has been removed the history
object, but provides useNavigate()
hook for route redirection. Sometime you need to redirect to a new route by js, you can use useNavigate()
to redirect.
import { useNavigate } from "react-router-dom";
let navigate = useNavigate();
navigate(`/home`);
// replace
navigate(`/home`, { replace: true });
// back
navigate(-1);
// navigate to a new route with object parameter
navigate({
pathname: "/home",
});
Router parametersโ
New version of React Router has remove the history
, location
and match
object, and also remove the withRouter
HOC.
search parametersโ
It provides the useSearchParams()
hook to get the parameters of the URL.
function Home() {
const [searchParams, setSearchParams] = useSearchParams();
searchParams.get("page"); //1
searchParams.get("size"); //10
return <div>HOme</div>;
}
Dynamic router parametersโ
<Route path="/user" element={<User />}>
<Route path=":/id" element={<UserDetail />} />
</Route>
After the preceding routes are configured, you can use useParams
hook in the
/user/123
.function UserDetail() {
const { id } = useParams();
return <div>id:{id}</div>;
}
State parametersโ
The state parameters can be passed when through <Link/>
, <NavLink/>
, or useNavigate()
as follows:
<Link to="/home" state={{ idx: 1, key: "JStyro" }}>
HOME
</Link>;
navigate("/home", { state: { idx: 1, key: "JStyro" } });
Now you can get the state parameters in the <Home/>
component by useLocation
hook.
function Home() {
const { state } = useLocation();
state.idx; // 1
state.key; // JStyro
return <div>้ฆ้กต</div>;
}
Summaryโ
I think the new version of React Router is better than the old version. But upgrading to React Router v6 is not easy. So I suggest you to use the new version in new projects. The old projects are not upgraded.