Navigation Between Components with React Router: Building a Smooth User Journey
Welcome to the realm of seamless navigation in React applications! In this comprehensive guide, we'll explore how to enable effortless navigation between components using React Router. Whether you're transitioning between pages, handling navigation links, or navigating programmatically, React Router provides the tools to create a smooth and responsive user journey.
Navigation Using Links
Basic Navigation Links:
Use the Link
component to create navigation links between different
components.
import React from 'react'
import { BrowserRouter as Router, Link, Route } from 'react-router-dom'
const Home = () => <h1>Home</h1>
const About = () => <h1>About</h1>
const Contact = () => <h1>Contact</h1>
const App = () => {
return (
<Router>
<nav>
<ul>
<li>
<Link to='/'>Home</Link>
</li>
<li>
<Link to='/about'>About</Link>
</li>
<li>
<Link to='/contact'>Contact</Link>
</li>
</ul>
</nav>
<Route path='/' exact component={Home} />
<Route path='/about' component={About} />
<Route path='/contact' component={Contact} />
</Router>
)
}
export default App
Styling Active Links:
Use the NavLink
component to add styles to active navigation links.
import { NavLink } from 'react-router-dom'
// ...
;<nav>
<ul>
<li>
<NavLink to='/' exact activeClassName='active-link'>
Home
</NavLink>
</li>
<li>
<NavLink to='/about' activeClassName='active-link'>
About
</NavLink>
</li>
<li>
<NavLink to='/contact' activeClassName='active-link'>
Contact
</NavLink>
</li>
</ul>
</nav>
Programmatic Navigation
Using useHistory Hook:
Navigate between components programmatically using the useHistory
hook.
import { useHistory } from 'react-router-dom'
const ProgrammaticNavigationButton = () => {
const history = useHistory()
const handleButtonClick = () => {
// Navigate to the "about" route
history.push('/about')
}
return <button onClick={handleButtonClick}>Go to About</button>
}
Navigating with Route Parameters
Using Link with Parameters:
Pass parameters in the URL using the Link
component.
<Link to='/user/johndoe'>John Doe's Profile</Link>
Accessing Parameters in Components:
Access the parameters in the rendered component using the match
object.
const UserProfile = ({ match }) => {
const { username } = match.params
return <h1>{username}'s Profile</h1>
}
Conclusion
Congratulations! You've now learned how to enable seamless navigation between components in React applications using React Router. Whether you're creating navigation links, styling active links, or navigating programmatically, React Router empowers you to build a user-friendly and dynamic user experience.