Bragon
Bragon

Reputation: 105

Function passed to child is being interpreted as a string

In React, I'm trying to get a value from a radio button transmitted from a child component to its parent. To this end I've created a function in the parent and passed it to the child as a prop:

handleOptionChange = e => {
  this.setState({
    selectedOption: e.target.value
  });
};

<RadioRental handleOptionChange="this.handleOptionChange" />;

This is what I have in the child:

class RadioRental extends Component {
  render() {
    return (
      <div className="form-check">
        <label>
          <input
            type="radio"
            name="react-tips"
            value="saloon"
            checked={this.props.selectedOption === "option_saloon"}
            onChange={this.props.handleOptionChange}
            className="form-check-input"
          />
          Saloon car
        </label>
      </div>
    );
  }
}

This produces the following compilation error:

index.js: 1446 Warning: ExpectedonChange listener to be a function, instead got a value ofstring type.

Any suggestions?

Upvotes: 0

Views: 118

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

You have to use {} notation in your parent:

<RadioRental handleOptionChange={this.handleOptionChange} />;
//------------------------------^-----------------------^

The {} notation sees things as JavaScript vs "" is string attribute.

Final Code

handleOptionChange = e => {
  this.setState({
    selectedOption: e.target.value
  });
};

<RadioRental handleOptionChange={this.handleOptionChange} />;

Upvotes: 3

Related Questions