How to navigate to the next page in React JS?

by mallory_cormier , in category: Javascript , a year ago

How to navigate to the next page in React JS?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 10 months ago

@mallory_cormier 

In React, the navigation between pages is typically handled using a library like React Router. Here are the steps to navigate to the next page using React Router:

  1. Install React Router: Run the following command in your project directory to install React Router:
1
npm install react-router-dom


  1. Set up the Router: Import the necessary components from React Router and set up the Router in your main file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import HomePage from './components/HomePage';
import NextPage from './components/NextPage';

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/next">Next Page</Link>
            </li>
          </ul>
        </nav>

        <Switch>
          <Route exact path="/" component={HomePage} />
          <Route path="/next" component={NextPage} />
        </Switch>
      </div>
    </Router>
  );
}

export default App;


In this example, the Router is set up with two routes - one for the home page (/) and one for the next page (/next). The Link component is used to create navigation links.

  1. Create the Components: Create the components for the home page and the next page.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import React from 'react';

function HomePage() {
  return (
    <div>
      <h1>Home Page</h1>
    </div>
  );
}

export default HomePage;


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import React from 'react';

function NextPage() {
  return (
    <div>
      <h1>Next Page</h1>
    </div>
  );
}

export default NextPage;


  1. Test the Navigation: You can now test the navigation between pages by running your React app. Clicking on the "Next Page" link should navigate to the next page.


Note: In more complex scenarios, you can use React Router's Route component with the render prop to conditionally render components based on certain conditions, such as passing props or handling route parameters.