reactjsreduxreact-reduxredux-formreact-redux-form

With react redux form, how can I style a hidden radio button's surrounding label?


With react redux-form, I have the following form:

    <form onSubmit={this.props.handleSubmit(this.handleSubmit.bind(this))}>
      <fieldset className="form-group">
        <Field name="job_title_id" component={errorMessage} />
        {this.props.job_titles.map(jobTitle => (
        <div className="form-check" key={jobTitle.id}>
          <label className="btn btn-secondary">
            <Field
              name="job_title_id"
              component="input"
              type="radio"
              value={jobTitle.id}
              checked={this.props.job_titles.id}
            />
            {' '}
            {jobTitle.title}
          </label>
        </div>
        ))}
      </fieldset>
      <div className="form-group">
        <button className="btn btn-primary" type="submit">Next</button>
      </div>
    </form>

For styling purposes, CSS is hiding the radio button. I need the field above the radio button know if the radio button is checked so I can add a class of ACTIVE to the label above:

if checked:

<label className="btn btn-secondary ACTIVE">

if not checked:

<label className="btn btn-secondary">

With react redux form, how can I style a hidden radio button's surrounding label?


Solution

  • Now I get it.

    The easy way to do that is keeping the radio checked status in state by onChange listener. So with this you put the class in the Label.

    constructor(props){
      super(props);
      ....  
      this.onRadioChange = this.onRadioChange.bind(this);
    
      this.state = {
        radioChecked: false
      }
    }
    
    onRadioChange (event) {
      this.setState({
        radioChecked: event.target.value
      });
    }
    ....
    <label className={(this.state.radioChecked ? "active": "" ) + " btn btn-secondary"}>
      <Field
        name="job_title_id"
        component="input"
        type="radio"
        value={jobTitle.id}
        checked={this.props.job_titles.id}
        onChange={this.onRadioChange}
      />
      {' '}
      {jobTitle.title}
    </label>
    ....
    

    I think this should works fine, even though I don't sure why you have to has a radiobutton, but ok :P.

    Maybe there is a better solution using Selecting Form Values Example.