Navigating between different views in a web application is crucial for creating a seamless user experience. In this guide, I’ll show you how to set up routing in a React application using BrowserRouter from react-router-dom. We’ll use Routes for defining routes and traditional anchor (<a>) tags for navigation.
First we need a application to work on. Click here to know how to create a react app.
Set Up Routing in React Using BrowserRouter
1.Install React Router:
run the following command in your terminal to install react router in your application.
npm install react-router-dom
the above command will install every dependencies that would be useful in routing.
2.Importing Library files in App.js:
we can’t use the router by installing react router ,we need to import them in our javascript file.
//App.js import React from 'react'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import Home from './Home';
- React: This library is necessary for building React components.
- BrowserRouter as Router: This component wraps the application to enable routing using the HTML5 history API.
- Route: This component defines the mapping between a URL path and a component.
- Routes: used to group multiple Route components.
- Home: This is a custom React component that will be rendered when the user navigates to the /home path.
3.Router and Anchor Tag in App.js:
//App.js function App() { return ( <> <a href="/home">Home</a> <Router> <Routes> <Route path="/home" element={<Home />} /> </Routes> </Router> </> ); } export default App;
- <>..</>: These are React fragments, which allow you to group multiple elements without adding extra nodes to the DOM.
- <a href=”/home”>Home</a>: This is a traditional HTML anchor (<a>) tag that links to the /home path. When clicked, it navigates to the Home page.
- <Router>: This component wraps around the part of the application where routing will be used. It enables the use of routing features like Routes and Route.
- <Routes>: This component groups multiple Route components. It replaces the older Switch component.
- <Route path=”/home” element={<Home />} />: This defines a route. When the URL path is /home, the Home component is rendered.
4.Adding Components:
we can create any number of components linked with a Anchor tag in App.js and it can contain any data as per your wish .Here, we have a single component (Home).After creating any new components, importing them our main javacript file is necessary .
//Home.js import React from 'react'; function Home() {return(<h1>Home Page</h1>)} export default Home;
5.Output:
page before routing:
page after routing: