React Router is a library that allows you to handle routing within a React application. It provides a way to map URLs to components, so that when a user navigates to a certain URL, the corresponding component will be displayed.
To get started with React Router, you'll first need to install it. You can do this by running the following command in your terminal:
npm install react-router-dom
Once you have React Router installed, you can import it into your application and start using it. Here is an example of how you might use React Router to handle routing in a simple application:
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
return (
<Router>
<Route path=\"/\" exact component={Home} />
<Route path=\"/about\" component={About} />
<Route path=\"/contact\" component={Contact} />
</Router>
);
}
In this example, we're using the BrowserRouter
component from React Router to handle client-side routing. We're also using the Route
component to define our routes. Each Route
component takes a path
prop, which is the URL that the route corresponds to, and a component
prop, which is the component that should be rendered when the route is accessed.
You can also pass props to the component using the render
method.
<Route path='/about' render={(props) => <About {...props} extra={extra} />} />
You can also use Link
component to navigate between different routes
import { Link } from 'react-router-dom';
<Link to=\"/about\">About</Link>
You can also use useParams
hook to extract parameter from the url
import { useParams } from \"react-router-dom\";
function User() {
let { id } = useParams();
return <h3>ID: {id}</h3>;
}
//in route
<Route path=\"/users/:id\" component={User} />
You can also use useLocation
hook to get current location information
import { useLocation } from \"react-router-dom\";
function useQuery() {
return new URLSearchParams(useLocation().search);
}
function About() {
let query = useQuery();
return (
<div>
<h2>About</h2>
<p>{query.get(\"message\")}</p>
</div>
);
}
This is just a basic example of how you can use React Router to handle routing in a React application. There are many other features and capabilities of React Router that you can explore, such as dynamic routing, nested routing, and protected routes.
For more information, please check the official documentation: https://reactrouter.com/web/guides/quick-start.