DEV Community

Erasmus Kotoka
Erasmus Kotoka

Posted on

1 1 1

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

Billboard image

Use Playwright to test. Use Playwright to monitor.

Join Vercel, CrowdStrike, and thousands of other teams that run end-to-end monitors on Checkly's programmable monitoring platform.

Get started now!

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay