- Install React Router π οΈ
npm install react-router-dom
- Set Up Router πΊοΈ
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
- Dynamic Routing π§©
<Route path="/user/:id" component={UserProfile} />
function UserProfile({ match }) {
return <div>User ID: {match.params.id}</div>;
}
- Nested Routes ποΈ
function Dashboard() {
return (
<Switch>
<Route path="/dashboard/profile" component={Profile} />
<Route path="/dashboard/settings" component={Settings} />
</Switch>
);
}
- Redirects & 404 π§
jsx
import { Redirect } from 'react-router-dom';
<Route path="/old-path">
<Redirect to="/new-path" />
</Route>
<Route path="*">
<NotFound />
</Route>
`
#COdeWith
#KOToka
Top comments (0)