September 27, 2021

React router example

A simple React Router example in this example we’ve 3 pages handled by the router, run the following code snippets. It enables the navigation among views of various components, in a react application.

import React, { Component } from 'react';
import { render } from 'react-dom';
import {BrowserRouter, Link} from 'react-router-dom';
import Main from './Main'
import './style.css';
class App extends Component {
 render() {
    return (
      <ul>
      <li><Link to="/">Home</Link></li>
     <li> <Link to="/one">One</Link></li>
      <li><Link to="/two">Two</Link></li>
         <Main />
      </ul>
    );
  }
}
render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));

In this section we’ve create all routes

import React from 'react';
import {Switch, Route} from 'react-router-dom';
import Home from './Home';
import PageOne from './PageOne';
import PageTwo from './PageTwo';
const Main=()=>{
  return (
     <Switch>
      <Route exact path="/" component={Home} />
          <Route exact path="/one" component={PageOne} />
          <Route exact path="/two/" component={PageTwo} />
     </Switch>
  )
}
export default Main;
import React from 'react';
const Home=()=>{
  return (
    <h1>Home</h1>
  )
}
export default Home;
import React from 'react';
const PageOne=()=>{
  return (
    <h1>Page 1</h1>
  )
}
export default PageOne;
import React from 'react';
const PageTwo=()=>{
  return (
    <h1>Page 2</h1>
  )
}
export default PageTwo;

Leave a Reply

Your email address will not be published. Required fields are marked *