Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are multiple ways to generate multiple pages in React, but one common approach is using React Router.

React Router is a library that allows developers to define multiple routes and map them to different components. This enables the creation of single-page applications with multiple views.

To use React Router, first, install it via npm:

npm install react-router-dom

Then import the necessary components in your main file:

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

The Router component is the top-level component that wraps all your routes. The Route component defines a mapping between a path and a component that should be rendered when that path is accessed. The Switch component wraps multiple Route components and ensures that only one of them is rendered at a time.

Here's a simple example of how to use React Router to render two different pages:

import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./pages/HomePage";
import AboutPage from "./pages/AboutPage";

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={HomePage} />
        <Route path="/about" component={AboutPage} />
      </Switch>
    </Router>
  );
}

In this example, the App component has two routes: one for the HomePage component (mapped to the path "/") and one for the AboutPage component (mapped to the path "/about"). When the user navigates to either of these paths, the corresponding component is rendered.

Note that the "exact" prop is used on the first Route component to ensure that it only matches the exact path ("/") and not any subpaths. This prevents unintentional matches and renders.

Using React Router, you can easily define and render multiple pages in your React application.