Routing in React js React-Router
What is routing?
You want websites where you’ve different paths and those different paths in the URL load different pages so that when the URL changes, we change the visible content of the page.
/welcome
/products
we can do this using different HTML files for different pages and those pages can be rendered by the browser but that approach is not good for using in react apps.
When we use different HTML pages, we don’t have a single page App, which means whenever we change the URL we leave our running client-side app, we lose all the state there. We have to wait for, to request responce cycle and we have to let the browser render this new page. And that’s one of the reasons why we switched to React.
- When building complex user interfaces, we typically build single-page applications (SPAs).
- Only one initial HTML request & responce
- Page(URL) changes are then handled by client-side (React) code.
- Changes the visible content without fetching a new HTML file.
We want a package, which does all that routing and which looks at the URL and brings different components onto the screen based on URL changes.
React Router
$ npm install react-router-dom
Create some different components for different urls
Products.js
const Products = ()=>{
return <h1>The Products Page </h1>
}
export default Products;
Welcome.js
const Welcome = ()=>{
return <h1>The Welcome Page </h1>
}
export default Welcome;
Home.js
const Home = ()=>{
return(
<div>
<h1> This is Home Page</h1>
</div>
)
}
export default Home;
Now import react-router-dom into our App.js file and implement routes for different links.
App.js
import {Route, Switch} from 'react-router-dom';
import Welcome from './Welcome'
import Products from './Products'
import Home from './Home'
function App() {
return (
<div>
<Switch>
{/* We use exact because it will implement route only for exact path not for others */}
<Route exact path="/">
<Home />
</Route>
<Route path="/welcome">
<Welcome />
</Route>
<Route path="/products">
<Products />
</Route>
</Switch>
</div>
);
}
export default App;
Now in our index.js file we have to import BrowserRouter so that it can read browser route paths.
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom'
import './index.css';
import App from './App';
ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));
Follow me for more
tush-tr.github.io
Github
Linked In
Twitter
Instagram