Search code examples
reactjsradio-buttonradio-group

Selecting <div> after clicked internal radio


In Radio Component the target behaviour is:

  • So when user click on the "RadioButton" diva area, radio input will be marked
  • 'default' radio styles are currently appearing - which should extend to the height and width of the entire RadioButton div

   const Radio = (props) => {
            return (
                <div className="RadioButton">
                        <div className="card mx-3 mb-3">
                            <div className="card-body hightlight">
                                <div className={"icon-type" + props.icon}></div>
                                <input id={props.id} onChange={props.changed} value={props.value} type="radio" checked={props.isSelected} />
                                {props.name}
                            </div>
                        </div>
                </div>
            );
        }

        export default Radio;

Solution

  • I would maintain the state of the selected radio through a parent component, which will be updated by a click handler passed via props from the parent to the radio child components, and attached to the outer div. Whether the input component is selected can be determined by looking at whether the selectedRadio, passed via props, matches the indentifier for that particular radio, also to be passed by props.

    const radioIds = [ ]; // whatever identifiers may be required
    
    Parent extends React.Component {
       constructor(props) {
         super(props);
         this.state = {
           selectedRadio = 1;
         }
    
        selectRadio = id => {
          this.setState({ selectedRadio: id });
        }
    
        render() {
           return (
               <div>
                  {radioIds.map(id => <Radio handleRadioSelect={this.radioSelect} id={id} selectedRadio={this.state.selectedRadio} />) // include other props
               </div> 
           )
        }
      }
    
    
    const Radio = (props) => {
        return (
            <div className="RadioButton" onClick={() => props.handleRadioSelect(props.id)>
                    <div className="card mx-3 mb-3">
                        <div className="card-body hightlight">
                            <div className={"icon-type" + props.icon}></div>
                            <input id={props.id} value={props.value} type="radio" checked={props.selectedRadio === props.id} />
                            {props.name}
                        </div>
                    </div>
            </div>
        );
    }