How to pass a function through props in React to a function in a different component?

Refresh

April 2019

Views

246 time

1

I am using this React radio group component to create radio groups. The radios are created by passing in a function to the RadioGroup component that will pass on the props to a new Radio component. For example (JSFiddle):

    <RadioGroup
      name={this.props.parameterData.param}
      selectedValue={this.state.selectedValue}
      onChange={this.handleChange}>
      {Radio => (
        <div>
          <Radio value='cool' label='First' />
          <Radio value='sweet' label='Second' />
        </div>
      )}
    </RadioGroup>

Now, I am trying to take iterate through an array of objects containing the value/label (JSFiddle):

renderRadios(options){
    let radioItems = [];
    for (let i = 0; i < options.length; i++) {
      const option = options[i];
      radioItems.push( <Radio value={option.value} label={option.label} /> )
    }
    return radioItems;
}
render() {
  return (
    <div>
      <h1>&x-{this.props.parameterData.param}={this.props.parameterData.default}</h1>
      <RadioGroup
        name={this.props.parameterData.param}
        selectedValue={this.state.selectedValue}
        onChange={this.handleChange}>
        {Radio => (
          <div>
            {Object.keys(this.props.options).map(this.renderRadios)}
          </div>
        )}
     </RadioGroup>
   </div>
  );
}

However, since Radio is not defined, I cannot do this. I've also tried putting the loop right in the Radio => function but I'm getting syntax errors. How can I accomplish this?

1 answers

1

You dont need render radios, all you need is

{Radio => (
    <div>
        {this.props.parameterData.options.map((option, index) => (
            <Radio value={option.value} label={option.label} key={index} />
        ))}
    </div>
)}