0

I am a newbie in React world. Actually, I come across a situation. When I use modern syntax, I am not getting things done. But, with bind.this method everything is working smoothly. Below is my code. Can you please find out mistakes. It giver error like "cant find state of undefined". Thank you.

import React, { Component } from 'react';

class Login extends Component {
    state = {
            email: '',
            password: '',
    }

    handleChange = e => {
        this.setState({ [e.target.name]: e.target.value });
      };

    signin(e) {
        e.preventDefault();
        const { email, password } = this.state;

        if (email === 'xyz@gmail.com'  && password === '123456') {
            console.log('logged in')
        } 
    }  

    render() {
        return(
            <div className='login'>
          <div className='login-div'>
          <form
            onSubmit={this.signin}>
            <fieldset>
              <h2 className='heading'>Sign into your account</h2>
              <label htmlFor="email">
                <input
                  type="email"
                  name="email"
                  placeholder="email"
                  value={this.state.email}
                  onChange={this.handleChange}
                />
              </label>
              <label htmlFor="password">
                <input
                  type="password"
                  name="password"
                  placeholder="password"
                  value={this.state.password}
                  onChange={this.handleChange}
                />
              </label>

              <button type="submit">Sign In!</button>
            </fieldset>
          </form>
          </div>
          </div>
        )
    }
}

export default Login;
Ali
  • 13
  • 5
  • Your signin() function declaration is missing the parameter part of the arrow notation `signin = (e) => {` – davidgamero Jul 09 '20 at 20:48
  • 1
    Does this answer your question? [React: "this" is undefined inside a component function](https://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function) – Emile Bergeron Jul 09 '20 at 20:48

2 Answers2

3

can you change your function to this

signin = (e) => {
        e.preventDefault();
        const { email, password } = this.state;

        if (email === 'xyz@gmail.com'  && password === '123456') {
            console.log('logged in')
        } 
    }  
Omar Sy
  • 486
  • 2
  • 8
0

Just to explain what's going on : It's because inside signin function, this refers to the context of the execution (the event handler) but not to your React component.

You can specify which this the signin function will be bound to using bind method. Add this line at the begining of the class :

this.signin = this.signin.bind(this);

Note : You can avoid binding all your functions by writing them using arrow function syntax.

aquinq
  • 1,318
  • 7
  • 18