Ask Your Question
4

What is the method for generating multiple pages in React?

asked 2021-07-02 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-03-14 00:00:00 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-07-02 11:00:00 +0000

Seen: 1 times

Last updated: Mar 14 '22