Reputation: 3816
I want to push some text to url route in onChange method of an input like this :
function Header(props) {
return (
<div>
<input type="radio" onChange={ (e)=> props.history.push(`/${e.target.value}`) } >
</div>
)
But it throws multiple errors and crashes :
TypeError: Cannot read property 'push' of undefined
How can use history.push properly or how can I push some text to route url manually from anywhere in react ?
Upvotes: 2
Views: 2034
Reputation: 29282
Error message suggests that history
prop is undefined
, meaning its not passed to your component as a prop which can happen depending on the hierarchy of the components in your app.
Use one of the following options to get access to history
:
Use useHistory
hook
import { useHistory } from 'react-router-dom';
function Header(props) {
const routerHistory = useHistory();
return (
<div>
<input type="radio" onChange={(e)=> routerHistory.push(`/${e.target.value}`)}>
</div>
)
}
Use withRouter
higher order component
import { withRouter } from 'react-router-dom';
function Header(props) {
return (
<div>
<input type="radio" onChange={(e)=> props.history.push(`/${e.target.value}`)}>
</div>
)
}
export default withRouter(Header);
For details on withRouter
and useHistory
, see:
Upvotes: 2