React Router is a popular library for handling navigation in React applications. It allows you to create a single-page application with dynamic, client-side routing. Here's a basic guide on how to use React Router for navigation:
Install React Router: You need to install React Router using npm or yarn. Open your terminal and run:
bashnpm install react-router-dom
or
bashyarn add react-router-dom
Set up BrowserRouter:
Wrap your entire application with BrowserRouter
. This component uses HTML5 history API to keep UI in sync with the URL.
jsx// index.js or App.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
Create Route Components:
Use the Route
component to define the mapping between a URL path and the React component that should be rendered.
jsx// App.js
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
const App = () => {
return (
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</div>
);
};
export default App;
In the above example, if the URL matches "/", the Home
component will be rendered. If it matches "/about", the About
component will be rendered, and so on.
Navigation:
Use the Link
component to create navigation links. When a Link
is clicked, it updates the URL without causing a full page reload.
jsx// Navigation.js
import React from 'react';
import { Link } from 'react-router-dom';
const Navigation = () => {
return (
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
);
};
export default Navigation;
Make sure to include this Navigation
component in your main layout or wherever you want the navigation to appear.
Handling 404 (Not Found):
Optionally, you can include a Route
without a path
prop to handle 404 errors.
jsx// App.js
// ... (previous code)
import NotFound from './NotFound';
const App = () => {
return (
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route component={NotFound} />
</Switch>
</div>
);
};
The NotFound
component will be rendered for any URL that doesn't match the routes defined.
That's a basic setup for using React Router in your application. Make sure to explore the React Router documentation for more advanced features and options: https://reactrouter.com/web/guides/quick-start