Languages
[Edit]
EN

React / react-router - basic routing example

0 points
Created by:
Dirask Community
5580

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 with command line inside your project.

npm install react-router-dom

 Then you have to import:

  • BrowserRouter as Router - that contains┬áthe routing configuration,
  • Switch - 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.

using the following code:

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

In below we create three┬á"pagesÔÇŁ┬áhandled by the react-router:

  • Home page,
  • Gallery,
  • About.

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

Simple routing example: 

// Note: Uncomment import lines during working with JSX Compiler.

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

// Pages to render --------------------

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>

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/gallery">
            <Gallery />
          </Route>
        </Switch>
      </div>
    </Router>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

You can run this example here. 

React - react-router

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