'Conditional rendering in radio button saves both values in the state

I'm new to react, I have conditional rendering in radio button,

  • lets say a ratio button has 2 options option1 and option2
  • on selection option1 the page shows up 2 text fields ( say first and last name )
  • on selection option2 the page shows up 2 buttons(saybtn1andbtn2`)
  • if i select option1 and fill up first & last name and hit save, it saved and if i come back to this page, it shows last filled first & last name
  • But later if I comeback and select option2, click on btn1 and hit save the state will hold first name, last name and option2 with btn1 pressed.
  • after saving option2 if i click option1, i can still see the first & last name filled
  • I have attached the sample code, all the fields are picked up from Django application

- the issue is, every ratio button options has its on number of components nested. how do toggle all the nested values of non selected options to null or default when the alternative option of the radio button is selected.

// Radio_button_field.js
import React from "react";
import {Col, FormGroup, Input, Label, Row} from "reactstrap";

export default class RadioButtonField extends React.Component {
    constructor(props) {
        super(props);
        let radioValues = {}
        this.props.options.forEach((el) => {
            let val = false
            if (el.value === "true") {
                val = true
            }
            radioValues = {
                ...radioValues,
                [el.title]: val
            }
        })
        if (this.props.value != null && this.props.value !== "") {
            radioValues[this.props.value] = true
        }
        this.state = {
            [this.props.name]: radioValues
        }
    }

    toggleRadioButton = (key) => {
        let propName = this.props.name
        let newRadioValues = Object.assign(...Object.keys(this.state[propName]).map(k => ({[k]: false})))
        if (this.state[this.props.name][key] !== true) {
            this.setState(prevState => ({
                [propName]: {
                    ...newRadioValues,
                    [key]: !prevState[propName][key]
                }
            }))
        }
        this.props.handleChange(this.props.name, key);
    }

    render() {
        let options = this.props.options
        let colItems = [], rowItems = []
        for (let i = 0; i < options.length; i++) {
            if (i % 2 !== 0) {
                colItems.push(i)
                colItems = []
            } else if (i % 2 === 0) {
                colItems.push(i)
                rowItems.push({colItems})
            }
        }
        return <FormGroup>
            <Label for={this.props.name}>{this.props.label} {this.props.required ? '*' : null}
                {this.props.error ? <p className={'text-danger'} style={{
                    fontWeight: 'normal',
                    fontSize: 12
                }}>{this.props.errorMessage}</p> : null}</Label>

            {rowItems.map((rowItem, rowIdx) =>
                <Row key={rowIdx}>
                    {rowItem.colItems.map((colItem, colIdx) =>
                        <Col key={colIdx}>
                            <Label className={'radio-button-label ' +
                            (this.state[this.props.name][options[colItem].title] ? 'radio-button-label-checked'
                                : '')} for={options[colItem].name}
                                   onClick={() => this.toggleRadioButton(options[colItem].title)}>{options[colItem].title}</Label>
                            <Input type="radio"
                                   name={options[colItem].name} id={options[colItem].name}
                                   style={{visibility: "hidden"}}/>
                        </Col>
                    )}
                </Row>
            )}
        </FormGroup>
    }
// handle change method where name will be Radio button name, value will be options of radio button
    handleChange = (name, value) => {
        this.setState(prevState => ({
            currStepResponses: {
                ...prevState.currStepResponses,
                [name]: value
            },
            dataSaved: false,
        }))
    }
// implementation page 
const myRadioButtonTag = <RadioButtonField name={el['name']}
                   placeholder={el['placeholder']}
                   label={el['label']}
                   options={el['options']}// will get the ratio button options
                   handleChange={this.handleChange}
                   value={currStepResponses[el['name']]}
                   error={errorFields[el['name']]}
                   errorMessage={FormFieldsHandling[el['name']] !== undefined ?                                      
                   FormFieldsHandling[el['name']]['message'] : ''}
                   required={CompulsoryFields.includes(el['name'])}/>

<Row>{myRadioButtonTag} </Row>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source