ReactJS: Radio button

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

See the Pen React Radio Button Component by Sandy Gifford (@SandoCalrissian) on CodePen.

interface IRadioButtonsProps {
	buttons: string[];
	selected?: string;
	onChange?: (value: string) => void;
}
interface IRadioButtonsState { }

class RadioButtons extends React.Component<IRadioButtonsProps, IRadioButtonsState> {
	private static count = 0;
	private id: number;
	private groupName: string;

	constructor(props: IRadioButtonsProps) {
		super(props);

		this.id = RadioButtons.count;
		RadioButtons.count++;

		this.groupName = `RadioButtons__${this.id}`;
	}

	public render(): React.ReactElement<any> {
		return (
			<div className="RadioButtons">
				{this.props.buttons.map((value, index) => {
					const inputID = `${this.groupName}__${index}`;
					return (
						<div key={index} className="RadioButtons__group">
							<input
								className="RadioButtons__group__input"
								type="radio"
								name={this.groupName}
								id={inputID}
								checked={this.props.selected === value}
								onChange={() => this.props.onChange(value)} />
							<label
								className="RadioButtons__group__label"
								htmlFor={inputID}>{value}</label>
						</div>
					);
				})}
			</div>
		);
	}
};

interface IAppProps { }
interface IAppState {
	selected: string;
}

class App extends React.Component<IAppProps, IAppState> {
	constructor(props: IAppProps) {
		super(props);

		this.state = {
			selected: "Option 1",
		};
	}

	public render(): React.ReactElement<any> {
		return (
			<div className="App">
				<RadioButtons
					buttons={["Option 1", "Option 2", "Option 3"]}
					selected={this.state.selected}
					onChange={(value) => {
						this.setState({
							selected: value,
						});
					}} />
			</div>
		);
	}
};

ReactDOM.render(<App />, document.getElementById("ReactWrapper"));
Series Navigation<< ReactJS: How to define a required textfield
ReactJS: Radio button and show selected >>