Page Routing in React

hello friends today I am going to tell you how you can do page routing in react. as you know it is frontend technology routing will be in browser only it wont do page reload. then how it works ? actually it manipulates the browser history and renders component on the fly.

lets see how it works in react#

For this i will use react-router-dom package which is very popular for routing in React. this gives some out of the box classes to handle routing like BrowserRouter , Switch, Route classes

will handle all outing logic, let’s see an example of this

first i have to install that package

$ npm install react-router-dom

for routing to work properly wrap your root component into BrowserRouter component so that all of your component switching will be happen inside this component

for example…

import {BrowserRouter as Router, Switch,Route, Link} from 'react-router-dom'
import Home from './Home'
import About from './About'
export default function App(){
    return(
        <div id="root">
            <h2>This header will display on every page </h2>\
            <Router>
                <Link to"/home">Home</Link>
                <Link to="/about">About</Link>
                ... more links
                <Switch>
                	<Route path="/home">
                	<Home />
                	</Route>
                	<Route path="/about">
                	<About />
                	</Route>
                </Switch>
                
            </Router>
        </div>
    )
}    

as you can see in above example all of your components will be in Switch block and based on route match it will switch the component.

Link will generate anchor <a> styled link but also prevent the page reloading.

comments powered by Disqus