Eduardo Gris
Eduardo Gris

Reputation: 31

Cannot read property 'push' of undefined - React error

I want to change my page when I click the button Login, but appears the error: Cannot read property 'push' of undefined. How to correct the code?

Here is my Login file:

import React from 'react';
import CreateUser from "./CreateUser";
import GetUser from "./GetUser";
import { BrowserRouter as Router, Link, Route} from 'react-router-dom';
import Routes from "./Routes";

export default class Login extends React.Component { //create Login class and export
  state = { // for hold all the values
    email: '',
    password: '',
  };

  change = e => {
    this.setState({
      [e.target.name]: e.target.value //grab name value and put here
    });
  };

  onSubmit = (e) => {
    e.preventDefault(); //avoid url change because of values
    this.props.onSubmit(this.state);
    this.props.history.push("/GetUser");
    this.setState({
      email: '',
      password: '',
    })
  };

//create a form
  render() {
    return (
      <form>
        <br / /*line breaks*/>
        Login
        <br />
        <br />
        <input
        name="email"
        placeholder='email' //appears in the field to write
        value={this.state.email} //input value
        onChange={e => this.change(e)} //allow change the value by typing
        />
        <br />
        <br />
        <input
        name="password"
        type='password' //hidden password type
        placeholder='password'
        value={this.state.password}
        onChange={e => this.change(e)}
        />
        <br/ >
        <br/ >
        <button onClick={e => this.onSubmit(e)} /*Login button*/>Login</ button>
        <br/ >
        <br/ >
        <button onClick={e => this.onSubmit(e)}/*Sign Up button*/>Sign Up</button>
  </form>
    );
  }
}

Here is my Routes file:

import React from 'react';
import { Router, Route } from 'react-router';
import App from './App';
import Login from './Login';
import CreateUser from './CreateUser';
import GetUser from './GetUser'

const Routes = (props) => (
  <Router {...props}>
    <Route exact path="/GetUser" component={GetUser}/>
    <Route exact path="/CreateUser" component={CreateUser}/>
  </Router>
);

export default Routes;

I'm new on React and really need help. I want to acess GetUser file after click the button.

Thx all, Eduardo Gris

Upvotes: 3

Views: 3899

Answers (1)

Tiago Alves
Tiago Alves

Reputation: 2316

In order to use the history object inside your component, you need to use the withRouter HOC from react-router-dom. For example:

import React from "react";
import {withRouter} from "react-router-dom";

class Login extends React.Component {
  ...
  onSubmit() {
    ...
    this.props.history.push("/GetUser");
  }
  ...
}
export default withRouter(Login);

Upvotes: 11

Related Questions