2

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 ?

2
  • Are you trying to change the route when radio input is changed? Commented Aug 21, 2020 at 14:53
  • @Yousaf yes sir Commented Aug 21, 2020 at 14:53

1 Answer 1

2

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.