tejesh
tejesh

Reputation: 89

TypeError: Cannot read property 'push' of undefined ReactJS

I am getting below error while using routing

         <Button
            variant="outlined"
            color="primary"
            //disabled={isDisabledSpec}
            onClick={this.handleSubmit}
            //onClick={this.handleSubmit.bind(this)}
          >

This is the button tag, where handleSubmit being called.

handleSubmit(e) {
    e.preventDefault();
    //const history = useHistory();
    this.props.history.push("/slider");
....}

This is handleSubmit function

Upvotes: 1

Views: 303

Answers (2)

SE32433
SE32433

Reputation: 91

You can follow the following steps to solve the problem

  1. import { withRouter } from 'react-router-dom';

  2. onClick={this.handleSubmit.bind(this)}

  3. handleSubmit = (e) => {
    e.preventDefault();
    this.props.history.push("/slider");}
    
  4. export default withRouter(component_name);

Upvotes: 2

akhtarvahid
akhtarvahid

Reputation: 9779

Did you wrap your component like this? if not wrap like this

import { withRouter } from 'react-router';

 class Specification extends Component {(...)}
 export default withRouter(Specification);

and if you don't bind your function then use the arrow function

handleSubmit = (e) => {
    e.preventDefault();
    this.props.history.push("/slider");
}

Upvotes: 2

Related Questions