DEV Community

Erasmus Kotoka
Erasmus Kotoka

Posted on

Routing and Navigation in React.js πŸš€

  1. Install React Router πŸ› οΈ
npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode
  1. 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>
  );
}
Enter fullscreen mode Exit fullscreen mode
  1. Dynamic Routing 🧩
<Route path="/user/:id" component={UserProfile} />

function UserProfile({ match }) {
  return <div>User ID: {match.params.id}</div>;
}
Enter fullscreen mode Exit fullscreen mode
  1. Nested Routes 🏞️
function Dashboard() {
  return (
    <Switch>
      <Route path="/dashboard/profile" component={Profile} />
      <Route path="/dashboard/settings" component={Settings} />
    </Switch>
  );
}
Enter fullscreen mode Exit fullscreen mode
  1. Redirects & 404 🚧

jsx
import { Redirect } from 'react-router-dom';

<Route path="/old-path">
  <Redirect to="/new-path" />
</Route>
<Route path="*">
  <NotFound />
</Route>
`
#COdeWith
#KOToka
Enter fullscreen mode Exit fullscreen mode

Top comments (0)