Home > Enterprise >  How to route someone to a page when they click a button: React
How to route someone to a page when they click a button: React

Time:11-18

From what I understand "Link" has been replaced with "Route" and Im having trouble find a solid answer or solution.

When a user clicks a button I want them to be routed to another page in my app '/trade'

Heres what I have so far

<button className='btn-success btn btn-lg' onClick={<Route to='/trade' />}>Trade This Stock</button>

CodePudding user response:

You can do this in many ways.

using useHistory

import React from "react";
import {useHistory, withRouter } from "react-router-dom";

function NavigationExample() {
  const history = useHistory();
  console.log(history);

  return (
    <div>
      <button onClick={() => history.push("/dashboard")} type="button">
        Click
      </button>
    </div>
  );
}
export default withRouter(NavigationExample);

App.js

import React from "react";
import { BrowserRouter as Router } from 'react-router-dom'; 
import NavigationExample from "./NavigationExample";

export default function App() {
  return (
    <Router>
      <NavigationExample />
    </Router>
  );
}

Live Example in Codesandbox

In above example, you import useHistory from react-router-dom. then take history object from useHistory and finally call history.push with url

using Link

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

function NavigationExample() {

return (
   <>
      <Link to={{pathname: '/dashboard'}}>Dashboard</Link>
   </>
  );
}
export default NavigationExample;

In above example, you import Link from react-router-dom. then you need to set to with url

CodePudding user response:

Navigate programmatically- react Tutorial

https://reactrouter.com/docs/en/v6/getting-started/tutorial#navigating-programmatically

import { useParams, useNavigate } from "react-router-dom";
import { getInvoice, deleteInvoice } from "../data";

export default function Invoice() {
  let navigate = useNavigate();
  let params = useParams();
  let invoice = getInvoice(parseInt(params.invoiceId, 10));

  return (
    <main style={{ padding: "1rem" }}>
      <h2>Total Due: {invoice.amount}</h2>
      <p>
        {invoice.name}: {invoice.number}
      </p>
      <p>Due Date: {invoice.due}</p>
      <p>
        <button
          onClick={() => {
            deleteInvoice(invoice.number);
            navigate("/invoices");
          }}
        >
          Delete
        </button>
      </p>
    </main>
  );
}
  • Related