Using React Router for Navigation | Javascript

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

const Home = () => <h1>Home</h1>;
const About = () => <h1>About</h1>;
const Contact = () => <h1>Contact</h1>;

const App = () => {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/about">About</Link></li>
            <li><Link to="/contact">Contact</Link></li>
          </ul>
        </nav>

        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
      </div>
    </Router>
  );
}

export default App;
 

AI Explanation

This code is a simple React application that uses React Router to handle routing within the application. Here's an explanation of the code: 1. The code imports the necessary components from the `react` and `react-router-dom` packages. - React: The core library for building the user interface in React applications. - BrowserRouter: Provides the high-level interface for managing the router in the application. - Route: Declares a route with a specific path and corresponding component. - Link: Provides a way to navigate between routes. 2. Three functional components are defined: Home, About, and Contact. These components just render a heading with the respective content. 3. The main component `App` is defined, which is a functional component that returns JSX. - Inside the `App` component, a `Router` component is used to wrap the route configuration. - A navigation menu is displayed with links to Home, About, and Contact pages using the `Link` component. - Three `Route` components are added to define the paths and the corresponding components to render when the paths match. 4. In the `Route` components: - The `path` attribute specifies the URL path of the route. - In the case of the Home route ("/"), the `exact` attribute is used to ensure that it matches only the exact URL path. - The `component` attribute specifies which component to render when the path matches. 5. Finally, the `App` component is exported as the default export. When this code is rendered in a React application, it will set up a simple navigation menu with three links that will render different components when clicked based on the route specified in the `Route` components.