Explore the power of React Router for seamless navigation in your React applications.
React Router is a powerful library that enables seamless navigation in React applications by managing the URLs in the browser.
To begin using React Router, you need to install it in your project by running:
npm install react-router-dom
Define routes in your app using the BrowserRouter
and Route
components:
import { BrowserRouter, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Route path='/home' component={Home} />
<Route path='/about' component={About} />
</BrowserRouter>
);
}
Nested routes can be achieved by nesting Route
components within other components.
Pass parameters in the route path and access them in your components:
<Route path='/users/:id' component={User} />
function User(props) {
const userId = props.match.params.id;
}
Use the history
object to navigate programmatically:
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
function handleClick() {
history.push('/new-page');
}
}
Redirect users to different routes using the Redirect
component:
import { Redirect } from 'react-router-dom';
function MyComponent() {
if (condition) {
return <Redirect to='/new-location' />;
}
}
React Router simplifies navigation in React applications, providing a declarative way to handle routing. Mastering React Router will enhance the user experience and overall performance of your app.