Steps to Implement BrowserRouter in React Router
Let’s create a simple React application with BrowserRouter:
Step 1: Install React Router
npm install react-router-dom
Step 2: Set up BrowserRouter in your application.
//Home.js
import React from 'react'
import { useNavigate } from 'react-router-dom'
const Home = () => {
const navigate=useNavigate()
const goabout=()=>{
navigate('/about')
}
return (
<div>
<h3>Welcome to home page</h3>
<button onClick={goabout}>Go to About page</button>
</div>
)
}
export default Home
//About.js
import React from 'react'
import { useNavigate } from 'react-router-dom'
const About = () => {
const navigate=useNavigate()
const gohome=()=>{
navigate(-1)
}
return (
<div>
<h3>Welcome to about us page</h3>
<button onClick={gohome}>Go to Home Page</button>
</div>
)
}
export default About
//UserDetail.js
import React from 'react'
import { useParams } from 'react-router-dom'
const UserDetail = () => {
const{userId}=useParams();
return (
<div>
<h1>User Details:</h1>
<p>User information is:{userId}</p>
</div>
)
}
export default UserDetail
//Userprofile.js
import React from 'react'
import { useNavigate } from 'react-router-dom'
const UserProfile = () => {
const navigate=useNavigate();
const logout=()=>{
navigate('/login')
}
return (
<div>
<h1>User Profile</h1>
<button onClick={logout}>Logout</button>
</div>
)
}
export default UserProfile
//useNavigation with useParams...
import React from 'react'
import { BrowserRouter as Router,Routes,Route ,Link} from 'react-router-dom'
import Home from './components/useNavigate/Home'
import About from './components/useNavigate/About'
import UserDetail from './components/useNavigate/UserDetail'
import UserProfile from './components/useNavigate/UserProfile'
const App = () => {
return (
<div>
<Router>
<nav>
<ul style={{display:'flex',gap:'20px'}}>
<li><Link to='/'>Home</Link></li>
<li><Link to='/about'>About</Link></li>
<li><Link to='/user/123'>User Details</Link></li>
<li><Link to='/profile'>User Profile</Link></li>
</ul>
</nav>
<Routes>
<Route path='/' element={<Home />}/>
<Route path='/about' element={<About />}/>
<Route path='/user/:userId' element={<UserDetail />}/>
<Route path='/profile' element={<UserProfile />}/>
</Routes>
</Router>
</div>
)
}
export default App
Output:
BrowserRouter in React
React Router is a powerful library for handling routing in React applications. BrowserRouter is a type of router provided by React Router that uses HTML5 history API to keep UI in sync with the URL. It enables declarative routing in React applications by mapping specific routes to components. In this article, we will explore BrowserRouter in React Router in depth. We’ll cover its features, advantages, and how to use it effectively in React applications.
Table of Content
- What is BrowserRouter in React Router?
- basename: string
- getUserConfirmation: func
- forceRefresh: bool
- keyLength: number
- children: node
- Key Features:
- Steps to Implement BrowserRouter in React Router
Contact Us