Reputation: 948
I know we can use to wrap our components but what is the way to route to a new page on click of a button in React functional components?
Upvotes: 0
Views: 288
Reputation: 9662
Try this,
React Router has now useHistory hook for functional components:
Docs: https://reacttraining.com/react-router/web/api/Hooks/usehistory
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button onClick={handleClick}>
Navigate
</button>
);
}
export default HomeButton;
Upvotes: 1
Reputation: 955
for this situations you can code like so :
import {withRouter} from 'react-router-dom';
const App = ({history , ...rest}) => {
const changeRoute = () => {
history.push("/new_route");
}
return (
<div>
<button onClick={changeRoute}>i will change route</button>
</div>
)
}
export default withRouter(App);
Upvotes: 0