0

I was learning React and wanted to use setState without putting it inside function and call it via bind() method like this:

<button onClick={this.setState.bind(this, {carName:'Honda'})}></button>

but I get an error.

react-dom.development.js:13825 Uncaught Error: Invalid argument passed as callback. Expected a function. Instead received: [object Object]

1
  • @Jai, react-dom.development.js:13825 Uncaught Error: Invalid argument passed as callback. Expected a function. Instead received: [object Object] Commented Feb 21, 2020 at 11:47

3 Answers 3

1

try using arrow function instead:

<button onClick={(e) => this.setState({carName : 'Honda'})}/>
Sign up to request clarification or add additional context in comments.

Comments

0

dont bind and use arrow function

<button onClick={(e) => this.setState({ carName:'Honda' })}></button>

Playground.js

import React, { Component } from 'react';

class Playground extends Component {
  render() {
    console.log('>>>>>  this.state : ', this.state);
    return (
      <div>
        <button type="button" onClick={() => this.setState({ carName: 'Honda' })}> try </button>
      </div>
    );
  }
}

export default Playground;

5 Comments

are you sure? without bind it would not result in error
@Jai yes it will work only if O/P is using class component
@Jai please check Playground.js in my answer it is working for me
@JayVaghasiya, sorry, is it true that onClick or any other event in React takes ONLY function?
@MII Yes you don't need binding
0

If you are using a Class component, by calling setState() in onClick(), you are calling setState in render() which is against React principles. You should call setState outside the render function.

The ideal approach is to call a handleClick function like below;

import React, { Component } from 'react';

state = {
 carName: null
}

handleClick = data => {
  this.setState({ carName: data.carName })
}

class Sample extends Component {
  render() {
    return (
      <div>
        <button type="button" onClick={() => this.handleClick({ carName: 'Honda' })}> try </button>
      </div>
    );
  }
}

export default Sample;

Secondly, you should not have .bind(this) in setState

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.