React Router in React JS

 React Router in React JS


React Router is a popular routing library for React that allows you to handle navigation and rendering of components based on the URL of your application. Here's an example of how to use React Router:

First, you need to install react-router-dom using npm:


sh

Copy code

npm install react-router-dom

Next, you can define the routes for your application:


jsx


import React from 'react';

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


import Home from './components/Home';

import About from './components/About';

import Contact from './components/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 use the BrowserRouter component from react-router-dom to define the routing for our application. We also use the Switch component to ensure that only one route is rendered at a time. Finally, we define the routes for our application using the Route component, which takes a path prop and a component prop that specifies the component to be rendered for that route.


Next, you can define the components for each of the routes:


jsx


import React from 'react';


function Home() {

  return <h1>Home Page</h1>;

}


function About() {

  return <h1>About Page</h1>;

}


function Contact() {

  return <h1>Contact Page</h1>;

}


export { Home, About, Contact };

In this example, we define three components, Home, About, and Contact, that will be rendered for the corresponding routes in our application.


When the application is loaded, the App component will render the appropriate component based on the current URL of the application. For example, if the URL is http://example.com/about, the About component will be rendered.


React Router provides a powerful way to handle navigation and rendering in your React application and can help make it easier to manage complex user interfaces.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...