Languages
[Edit]
EN

React / react-router 6 - basic routing example

13 points
Created by:
Aston-Freeman
787

In this article, we would like to show you a basic routing example in React.

To use routing in React, the first thing you need to do is install react-router-dom@6 with command line inside your project.

npm install react-router-dom@6

Then you have to import:

  • BrowserRouter (e.g. as Router) - that contains core routing logic,
  • Routes - that searches through its children (<Route> elements) to find the one whose path matches the current URL,
  • Route - to render some components when its path matches the current URL,
  • Link - to navigate through the routes.

By using the following code:

import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';

In below example we create three pages handled by the react-router:

  • Home page,
  • Gallery page,
  • About page.

As we click on the different <Link> components, the router renders the matching <Route> components.

Simple routing example:

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';

// Pages ----------------------

const Home = () => {
  return <h2>Home</h2>;
};

const Gallery = () => {
  return <h2>Gallery</h2>;
};

const About = () => {
  return <h2>About</h2>;
};

// Routing --------------------

const App = () => {
  return (
    <Router>
      <div>
        <div>
          <Link to="/">Home</Link>
          <Link to="/gallery">Gallery</Link>
          <Link to="/about">About</Link>
        </div>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/gallery" element={<Gallery />} />
        </Routes>
      </div>
    </Router>
  );
};

export default App;

References

  1. https://reactrouter.com/docs/en/v6/getting-started/overview 

Alternative titles

  1. React / react-router v6 - basic routing example
  2. React - redirect to another route using react-router 6
  3. React - redirect to another route using react-router v6
  4. React - react-router 6 example
  5. React - react-router v6 example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join