React Router

Cho Zin Thet
Nov 2, 2020
  • create a react app
  • install react router dom package
  • import the dependencies
  • create routes to components
  • the complete code

Basic react router

  • create a react app
npx create-react-app react-router-test
  • install react router dom package
npm install react-router-dom
  • import the dependencies
import { 
BrowserRouter as Router,
Switch,
Route,
Link } from 'react-router-dom';
  • create routes to components
function App(){
return <Router>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
<Switch>
<Route path="/about"><About/></Route>
<Route path="/contact"><Contact/></Route>
<Route path="/"><Home/></Route>
</Switch>
</Router>}

Complete code

App.jsx

import React from 'react';
import About from './Male';
import Contact from './Female';
import {
BrowserRouter as Router,
Switch,
Route,
Link } from 'react-router-dom';
function Home(){
return <h1>This is home page. click other tags</h1>
}
function App(){
return <Router>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
<Switch>
<Route path="/about"><About/></Route>
<Route path="/contact"><Contact/></Route>
<Route path="/"><Home/></Route>
</Switch>
</Router>
}
export default App;

About.jsx

import React from 'react';function About(){
return <div>
<h1>About Tag</h1>
</div>
}
export default About;

Contact.jsx

import React from 'react';function Contact(){
return <div>
<h1>Contact Tag</h1>
</div>
}
export default Contact;

--

--