Routing in React allows you to navigate between different views or pages in a single-page application (SPA) without the need for page reloads. There are several libraries available for handling routing in React, with React Router being the most popular choice. Below, I’ll outline how to set up routing using React Router:
1. Install React Router:
First, install React Router in your project using npm or yarn:
npm install react-router-dom
yarn add react-router-dom
2. Define Routes:
In your main component (usually `App.js`), define the routes using the `BrowserRouter`, `Route`, and `Switch` components from React Router:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
import NotFound from './components/NotFound';
function App() {
return (
<Router>
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
{/* Handle 404 - Not Found */}
<Route component={NotFound} />
</Switch>
</div>
</Router>
);
}
export default App;
3. Create Components:
Create separate components for each route. For example:
import React from 'react';
function Home() {
return <h2>Home</h2>;
}
export default Home;
// About.js
import React from 'react';
function About() {
return <h2>About</h2>;
}
export default About;
// Contact.js
import React from 'react';
function Contact() {
return <h2>Contact</h2>;
}
export default Contact;
// NotFound.js
import React from 'react';
function NotFound() {
return <h2>404 - Not Found</h2>;
}
export default NotFound;
4. Navigation:
You can add navigation links using the `Link` component provided by React Router:
import { Link } from 'react-router-dom';
function Navbar() {
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 Navbar;
5. Route Parameters:
You can define dynamic routes with parameters using `Route` components with a path containing `:paramName`.
<Route path=”/users/:userId” component={UserDetail} />
Then, access the parameter in the component using `props.match.params.paramName`.
React Router provides many more features like route guarding, redirects, history manipulation, etc.