ReactJS: Radio button and show selected

This entry is part 31 of 35 in the series React JS

See the Pen React Radio Buttons by Nick Van Dyck (@nickvdyck) on CodePen.

const RadioGroup = ({ name, value, children, onChange, ...rest }) => {
  const checked = typeof onChange === "function" ? "checked" : "defaultChecked";
  return (
    <div onChange={onChange}>
      {children.map(child =>
        React.cloneElement(child, {
          [checked]: child.props.value === value,
          name,
          ...rest
        })
      )}
    </div>
  );
};

const RadioButton = ({ label, value, className, ...rest }) => (
  <label className={className}>
    <input type="radio" value={value} {...rest} />
    {label}
  </label>
);

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selected: "",
      fruits: ["Grape", "Apple"]
    };

    this.resetSelection = this.resetSelection.bind(this);
    this.changeFruit = this.changeFruit.bind(this);
    this.showSelected = this.showSelected.bind(this);
  }

  showSelected() {
    alert(`Current selection: ${this.state.selected || "none"}`);
  }

  changeFruit(event) {
    this.setState({ selected: event.target.value });
  }

  resetSelection() {
    this.setState({ selected: "" });
  }

  render() {
    return (
      <div>
        <RadioGroup
          name="fruit"
          onChange={this.changeFruit}
          value={this.state.selected}
        >
          {this.state.fruits.map(fruit => (
            <RadioButton value={fruit.toLowerCase()} label={fruit} />
          ))}
        </RadioGroup>
        <br />
        <button onClick={this.resetSelection}>Reset Selection</button>
        <button onClick={this.showSelected}> Show Selected </button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));
Series Navigation<< ReactJS: Radio button
ReactJS: Simple List >>