Skip to main content

Navigating with React Router: Basic guidance

In this concise guide, we’ll explore the fundamental components of React Router DOM and learn how to create smooth navigation within React applications.

There are three key components: <Router>, <Route>, and <Link>

The <Router> Component

The <Router> component serves as the backbone of React Router. It provides the routing functionality for your entire application. Here’s how to use it:

import { BrowserRouter as Router, Route } from 'react-router-dom';

function App() {
return (
<Router>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
{/* Add more routes */}
</Router>
);
}

Wrap your entire app with <Router> to enable navigation between different views.

Each <Route> corresponds to a specific URL path and renders the associated component.

The <Route> Component

The <Route> component dynamically renders UI components based on the current URL. Here’s a basic example:

import { Route } from 'react-router-dom';

function Home() {
return <h1>Welcome to the Home Page!</h1>;
}

function About() {
return <h1>About Us</h1>;
}

// Usage in App component
<Route path="/" component={Home} />
<Route path="/about" component={About} />

The <Link> component creates navigation links within your app. It replaces traditional anchor tags (<a>) and ensures smooth client-side navigation without page reloads:

import { Link } from 'react-router-dom';

function Navigation() {
return (
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
{/* Add more navigation links */}
</ul>
</nav>
);
}