Working with react-router-dom


React Router has been broken into three packages: react-router, react-router-dom, and react-router-native. For webpages you need to use react-router-dom
and for mobile apps you need to use react-router-native. react-router is exported in both of these components.

npm install --save react-router-dom  

Two types of Router

*  <BrowserRouter>
*  <HashRouter>

Router components only expect to receive a single child element. To work within this limitation, it is useful to create an component that renders the rest of your application

Changes in the main component
import { BrowserRouter } from 'react-router-dom'

    <App />
), document.getElementById('root'))
Actual routing settings.
<Route path='/aboutus'/>  
<Route exact path='/aboutus'/>  
  • When the pathname is ‘/’, the path does not match
  • When the pathname is ‘/aboutus’ or ‘/aboutus/xyz’, the path matches
  • If you only want to match ‘/aboutus’, then you need to use the “exact” prop.

I have added these changes in my layout file

  <Route exact path='/' component={Home}/>
  <Route path='/aboutus' component={AboutUs}/>
  <Route path='/contactus' component={ContactUs}/>
add these changes in required component. I have added these in my Navbar.js
        <li><Link to='/'>Home</Link></li>
        <li><Link to='/aboutus'>About Us</Link></li>
        <li><Link to='/contactus'>Contact Us</Link></li>

Leave a Reply

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