How to use React Router for navigation?

  1. Install React Router by running the following command in your terminal:
npm install react-router-dom
  1. Import the necessary components from React Router in your App.js file:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
  1. Create your different components that will represent different pages in your application. For example, you can create a Home component and a About component.

  2. Inside your App component, wrap your entire application with the Router component:

function App() { return ( <Router> <div className="App"> {/* Your routes go here */} </div> </Router> ); }
  1. Define the routes for your different components inside the Switch component. Each Route component should have a path and a component prop that specifies which component to render when that path is accessed.
function App() { return ( <Router> <div className="App"> <Switch> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </Switch> </div> </Router> ); }
  1. Now you can create navigation links in your components using the Link component. For example, in your Home component:
import { Link } from 'react-router-dom'; function Home() { return ( <div> <h1>Home Page</h1> <Link to="/about">Go to About Page</Link> </div> ); } export default Home;
  1. You can now navigate between different pages in your application by clicking on the navigation links you've created. React Router will handle the rendering of the appropriate component based on the path specified in the Route component.