React Router

React Router is a popular routing library for React that allows developers to create single-page applications with multiple views and routes. Here’s an example of how to use React Router in a simple application:

First, you’ll need to install React Router using npm or yarn:

				
					npm install react-router-dom
				
			

or

				
					yarn add react-router-dom
				
			

Once you’ve installed React Router, you can use it to define routes in your application. Here’s an example:

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

import Home from './Home';
import About from './About';
import Contact from './Contact';

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
      </Switch>
    </Router>
  );
}

export default App;

				
			

In this example, we’re using the BrowserRouter component from React Router to define the routing for our application. Inside the BrowserRouter, we’re using the Switch component to define multiple Route components, each with a different path and component prop. The path prop defines the URL path for each route, and the component prop defines the component that should be rendered when that route is matched.

In this example, we’ve defined three routes:

  • The / route, which matches the home page of our application and renders the Home component.
  • The /about route, which matches the about page of our application and renders the About component.
  • The /contact route, which matches the contact page of our application and renders the Contact component.

To use this component, you would render it in your app, like this:

				
					import React from 'react';
import App from './App';

function Main() {
  return (
    <div>
      <h2>Welcome to my app!</h2>
      <App />
    </div>
  );
}

export default Main;

				
			

In this example, we’re defining a functional component called Main that renders the App component, along with a title for the app using an <h2> element.

Overall, React Router is a powerful and flexible way to handle routing in React applications. By using the BrowserRouter, Switch, and Route components, you can define complex routing rules that allow your users to navigate your application with ease.

Join To Get Our Newsletter
Spread the love