Explore the power of React Router for seamless navigation in your React applications. Learn how to set up routes, handle dynamic routing, and optimize user experience.
React Router is a vital tool for managing navigation in React applications. Let's delve into the key aspects of React Router:
npm install react-router-dom
Define routes in your main component:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
</Switch>
</Router>
);
}
<Route path='/user/:id' component={User} />
function User(props) {
const { id } = props.match.params;
return <div>User ID: {id}</div>;
}
import { useHistory } from 'react-router-dom';
function Home() {
const history = useHistory();
const handleClick = () => {
history.push('/about');
};
return (
<button onClick={handleClick}>Go to About</button>
);
}
<Route path='/products' component={Products} />
function Products() {
return (
<div>
<h3>Products</h3>
<Route path='/products/:id' component={ProductDetails} />
</div>
);
}
Mastering React Router empowers you to create dynamic and user-friendly navigation experiences in your React applications.