Search code examples
reactjsradiobuttonlist

REACT.js initial radio select


I have been trying to modify existing code by adding a few of new functionalities. I have this function that renders set of radiobuttons based on variable ACCREDITATION_TYPES:

createRadioCalibration(name) {
    const { id, value, labels } = this.props;
    const _t = this.props.intl.formatMessage;

    const ACCREDITATION_TYPES = [
        [CALIBRATION_ACCREDITED, _t(messages.calibrationAccredited)],
        [CALIBRATION_NOT_ACCREDITED, _t(messages.calibrationNotAccredited)]
    ];

    return  <FormChoiceGroup
                    type = "radio"
                  values = {ACCREDITATION_TYPES.map(mapValueArray)}
                     key = {`${id}_${name}`}
                    name = {`${id}_${name}`}
                   value = {value[name]}
            handleChange = {this.handleFieldChangeFn(name)}
            />;
}

The radios by default are all unchecked. When clicked this function is fired up:

handleFieldChangeFn(name) {
    return (e) => {
        const { handleFieldChange, id } = this.props;
        handleFieldChange(id, name, e.target.value);
    };
}

The form is rendered as follows:

render () {

    const FIELDS = {
        [CALIBRATION]: this.createRadioCalibration(CALIBRATION),
    };

    return (
        <div className="">
           <label>{_t(messages.calibration)}</label>
           { FIELDS[CALIBRATION] }

How can I select any option I want as an initial state? There are only two options now but what if there were five? Also how can I manipulate the radio selection based on onChange event of other elements of the form, namely a drop down menu?


Solution

  • Answering my question I got two minuses for asking: in the constructor one needs to add the following this.props.handleFieldChange( 'id', 'radio_button_group_name', 'value_of_the_output_that_should_be_selected' );

    That will select particular radio in a loop.