MII
MII

Reputation: 979

React - onClick 'expected function, recieved object'

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]

Upvotes: 0

Views: 325

Answers (3)

Afia
Afia

Reputation: 683

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

Upvotes: 0

Jay
Jay

Reputation: 3117

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;

Upvotes: 0

Molly
Molly

Reputation: 1907

try using arrow function instead:

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

Upvotes: 1

Related Questions