Routing is an essential process for handling communication between computers. It's how we navigate through websites and web applications.
React Router is a routing solution for React apps that leverages the web address (URL) to determine which component(s) should render on the screen.
Key components of React Router:
Basic setup example:
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom'
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
<Link to="about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="about" element={<About />} />
</Routes>
</BrowserRouter>
)
}
URL parameters allow you to create dynamic routes that can capture values from the URL and use them within your components.
path="users/:userId"
useParams
hookExample of using URL parameters:
// Route definition
<Route path="users/:userId" element={<UserProfile />} />
// In the UserProfile component
import { useParams } from 'react-router-dom'
function UserProfile() {
const { userId } = useParams()
// Now use userId to fetch specific user data
return <h2>Profile for user {userId}</h2>
}
Sometimes you need to navigate users to a new route based on some event (like form submission or button click) rather than a direct link click.
useNavigate
hook to get a navigation functionreplace: true
to replace the current history entryExample of programmatic navigation:
import { useNavigate } from 'react-router-dom'
function LoginForm() {
const navigate = useNavigate()
const handleSubmit = (e) => {
e.preventDefault()
// Login logic
// ...
// After successful login, redirect to dashboard
navigate('/dashboard')
}
return (
<form onSubmit={handleSubmit}>
{/* form fields */}
<button type="submit">Login</button>
</form>
)
}
Complete the React Router project to demonstrate your understanding of routing in React applications.
Project Instructions Project Repository