Tani
Tani

Reputation: 17

How do I route my button to another page using react-router-dom?

I have a Nutrition facts button on my page that when clicked can route to another page on my site that lists the nutrition facts. How do I make this happen?

Upvotes: 0

Views: 34

Answers (1)

gdh
gdh

Reputation: 13702

  • Basically you need to use react-router-dom package and make use of BrowserRouter and Route and Switch and define your routes.
  • Then you need wrap your button with Link and indicate where to route to.

Your app component

import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import NutritionPage from "./components/NutritionPage";
import NutritionFacts from "./components/NutritionFacts";

function App() {
  return (
    <Router>
      <Switch>
          <Route path='/' exact component={NutritionPage}></Route>
          <Route path='/nutrition-facts' component={NutritionFacts}></Route>
      </Switch>
    </Router>
  );
}

export default App;

NutritionPage Component

import React from 'react';
import {Link} from "react-router-dom";

const NutritionPage = (props) => {
    return (<div>
        <h2>My Nutrition Page</h2>
        <Link to='/nutrition-facts'><button>Nutrition Facts</button></Link>
    </div>)
};

export default NutritionPage;

NutritionFacts Component

import React from 'react';

const NutritionFacts = (props) => {
    return (<div>Nutrition Facts List Page</div>)
};

export default NutritionFacts;

For more details and examples read the docs

Upvotes: 1

Related Questions