
What is React Router?
React router is the routing library in react. Router can be used to synced the UI with the URL.
To install Run following command in your project path
npm install react-router-dom
In order to work with router you have to surround your app with <BrowseRouter> tag. Open index.js file
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
)
Then in yout app Component add the switch element to ensure that render only one component at a time.
function App() {
return (
<main>
<Switch>
</Switch>
</main>
)
}
Now it’s time to add paths and components. We can use Router element.first import your components into app component. example as below
import Home from './components/Home';
function App() {
return (
<main>
<Switch>
<Route exact path="/" component={Home Page} exact />
<Route exact path="/about" component={Contact Us} />
<Route exact path="/shop" component={More Details} />
</Switch>
</main>
)
}
If you want to open a component with a link clicked <Link> element cab be used.example if you want to render Contact Us component
<li>
<Link to="/ContactUs">Contact Us</Link>
</li>
Adding 404 Page

404 Not found page can be added when user tries to request a page which in not available. for that you have to create a component just like other component with the styles you want. then add the component as Below. My 404 component name is NotFound
function App() {
return (
<main>
<Switch>
<Route exact path="/" component={HomePage} exact />
<Route exact path="/about" component={ContactUs} />
<Route exact path="/Details" component={MoreDetails} />
<Route component={NotFound} />
</Switch>
</main>
)
}
Lets meet in another Post Soon!!!
Leave a comment