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>
);
}
In above example, you import
useHistory
fromreact-router-dom
. then take history object fromuseHistory
and finally callhistory.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
fromreact-router-dom
. then you need to setto
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>
);
}