Vadim
Vadim

Reputation: 13

React click handler passed to child component is not working

I've tried to pass click handler to SignIn component, but it doesn't work for me. I get log and then page refreshes

Auth class:

class Auth extends Component {

login() {
    console.log('Clicked'); //only this method works
    fetch('/api/auth/signin', {
        method: 'POST',
        body: JSON.stringify(this.state),
        headers: {
            'Content-Type': 'application/json; charset=utf8'
        }
    }).then((response) => {
        if (response.status === 200) {
            this.props.history.push('/api/categories')
        }
    })
}

render() {
    return (
        <SignIn onCustomClick={this.login}/> //onClick handler
    )
}

SignIn component

export default function SignIn(props) {
    const {onCustomClick} = props; // props
      return (
              <Button
                type="submit"
                fullWidth
                variant="contained"
                color="primary"
                className={classes.submit}
                onClick={onCustomClick} // onClick handler
              >)
    }

Upvotes: 1

Views: 110

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281646

You need to bind your login function to the class context. Write it as an arrow function to achieve that.

Also add e.preventDefault to prevent the default browser behaviour on form submit to refresh the page with submitted information

class Auth extends Component {

    login = (e) =>  { // Arrow function here
        e.preventDefault(); // prevent default browser behaviour to refresh
        fetch('/api/auth/signin', {
            method: 'POST',
            body: JSON.stringify(this.state),
            headers: {
                'Content-Type': 'application/json; charset=utf8'
            }
        }).then((response) => {
            if (response.status === 200) {
                this.props.history.push('/api/categories')
            }
        })
    }

    render() {
        return (
            <SignIn onCustomClick={this.login}/> //onClick handler
        )
    }

}

Upvotes: 1

Nurul Sundarani
Nurul Sundarani

Reputation: 7558

Your login function is not binded, you can use arrow functions or explicitly bind it in the constructor for it to work.

class Auth extends Component {
constructor(props){
  super(props);
  // here your function is binded
  this.login = this.login.bind(this);
}

login() {
    console.log('Clicked'); //only this method works
    fetch('/api/auth/signin', {
        method: 'POST',
        body: JSON.stringify(this.state),
        headers: {
            'Content-Type': 'application/json; charset=utf8'
        }
    }).then((response) => {
        if (response.status === 200) {
            this.props.history.push('/api/categories')
        }
    })
}

render() {
    return (
        <SignIn onCustomClick={this.login}/> //onClick handler
    )
}

Upvotes: 0

Related Questions