Stateless component React router
In 2019, React Router v4 has now added the useHistory hook for stateless / functional components:
https://reacttraining.com/react-router/web/api/Hooks/usehistory
From the docs:
import { useHistory } from "react-router-dom";function HomeButton() { let history = useHistory(); function handleClick() { history.push("/home"); } return ( <button type="button" onClick={handleClick}> Go home </button> );}
It worked for me by using withRouter, (plus ignoring typescript warning):
import { withRouter } from 'react-router-dom';...type Props = { myProp: boolean };// @ts-ignoreexport const MyComponent: FC<Props> = withRouter(({ myProp, history }) => {...})
You can directly import the history object and push from that. For example try below code.
import React from "react"; // eslint-disable-line no-unused-varsimport "bootstrap/dist/css/bootstrap.min.css";import "./header.css";import history from "/your/history/path" //try thisconst Header = () => ({ handleAuthor() { history.push('/somepath')// change to this }, render(){ return ( <div className = "header"> <h1 onClick = {this.handleAuthor.bind(this)}>{this.props.headerText}</h1> </div> ); } });export default Header;
Create browser history like below and use it every where by importing.
import createBrowserHistory from 'history/createBrowserHistory';export default createBrowserHistory({});