0

I have a sample code for Signing page as follows, When I am typing the username and passwords inside the text fields with every character the onClick event of the button is triggered and I can see the output of console.log(). Why it is triggered?

class Signin extends React.Component {
  state = {
    username: null,
    password: null,
  }
  render () {
    const { t, classes } = this.props;
    return (
      <div >
        <div >
          <div >
            <Card>
              <CardContent>
                <form>
                  <TextField
                    inputProps={{ style:{fontSize:20, textAlign:'center', direction:'ltr'} }}
                    value={this.state.username}
                    onChange={e => this.setState({username: e.target.value})}
                    id="username"
                    label={t("Username")}
                    className={classes.textField}
                    fullWidth
                    margin="normal"
                  />
                  <TextField
                    inputProps={{ style:{fontSize:20, textAlign:'center', direction:'ltr'} }}
                    value={this.state.password}
                    onChange={e => this.setState({password: e.target.value})}
                    id="password"
                    label={t("Password")}
                    className={classes.textField}
                    type="password"
                    fullWidth
                    margin="normal"
                  />
                  <Button variant="raised" color="primary" fullWidth type="submit" onClick={console.log(this.state.username,this.state.password)} >{t("Login")}</Button>
                </form>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    );
  }
}
rahram
  • 560
  • 1
  • 7
  • 21

2 Answers2

1

Change your console.log from:

 onClick={console.log(this.state.username,this.state.password)}

to like this below:

 onClick={() => console.log(this.state.username,this.state.password)}
Kiran LM
  • 1,359
  • 1
  • 16
  • 29
emzki
  • 88
  • 7
1

try this it is happening because It depends on where exactly are you using the Arrow function. If the Arrow function is used in the render method, then they create a new instance every time render is called just like how bind would work.

<Button 
variant="raised" 
color="primary" 
fullWidth type="submit" 
onClick={()=>{console.log(this.state.username,this.state.password)} >{t("Login")}}</Button>
Abhi Patel
  • 214
  • 1
  • 6
  • 1
    https://stackoverflow.com/questions/45053622/how-to-avoid-bind-or-inline-arrow-functions-inside-render-method/45053753#45053753 this may help more – Abhi Patel Oct 31 '19 at 06:25