Route, Link, and NavLink in React
Key Concepts
- Route
- Link
- NavLink
Route
The Route
component in React Router is used to define the mapping between a URL path and a component. When the URL matches the specified path, the corresponding component is rendered.
Example:
import { BrowserRouter as Router, Route } from 'react-router-dom'; import Home from './Home'; import About from './About'; function App() { return ( <Router> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </Router> ); }
In this example, the Home
component is rendered when the URL is "/", and the About
component is rendered when the URL is "/about".
Link
The Link
component is used to create navigation links within your application. It prevents the default browser behavior of a full page reload and instead updates the URL and renders the appropriate component based on the new URL.
Example:
import { Link } from 'react-router-dom'; function Navigation() { return ( <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> ); }
In this example, clicking on the "Home" link will navigate to the root URL "/", and clicking on the "About" link will navigate to "/about".
NavLink
The NavLink
component is a special version of Link
that adds styling attributes to the rendered element when it matches the current URL. This is useful for creating navigation menus where the active link is highlighted.
Example:
import { NavLink } from 'react-router-dom'; function Navigation() { return ( <nav> <NavLink to="/" exact activeClassName="active">Home</NavLink> <NavLink to="/about" activeClassName="active">About</NavLink> </nav> ); }
In this example, the "active" class is applied to the NavLink
that matches the current URL, allowing you to style the active link differently.
Analogies
Think of the Route
component as a map that tells React which component to display based on the current location. The Link
component is like a door that allows you to move between different locations without leaving the house. The NavLink
component is a special door that lights up when you're in the room it leads to, making it easy to see where you are.
Another analogy is a restaurant menu. The Route
component is the menu that lists all the dishes (components) available. The Link
component is the waiter who takes your order (click) and brings you the dish (component). The NavLink
component is a special waiter who highlights the dish you've ordered, so you know what you're eating.