Tim
Tim

Reputation: 709

Radio button not working

I have created a radio component but when clicked it does'nt show checked here is the code

import React from 'react';
import classnames from 'classnames';

const RadioButton = (field) => {

  const inputClasses = classnames('form-group  has-feedback  ',{
    'has-error': field.meta.touched && field.meta.error,
  });
  return(
    <div className={inputClasses}>
        <label className="radio-inline custom-radio nowrap">
        <input
          disabled={field.disabled}
          type="radio"
          name={field.input.name}
          value={field.input.value}
          defaultChecked={field.defaultChecked}
          {...field.input}
        />
        <span>{field.label}</span>
      </label>
    </div>
  );
};

export default RadioButton;

here is the field:

                      <Field
                        label="True"
                        component={RadioButton}
                        name="True"
                        type="radio"
                        value={true}
                       defaultChecked={ true }
                      />
                      <Field
                        label="False"
                        component={RadioButton}
                        name="False"
                        type="radio"
                        value={false}
                        defaultChecked={ false }
                      />

this is the warning i am getting on console: Warning: RadioButton contains an input of type radio with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props

can anyone help me out with this?

Upvotes: 3

Views: 18011

Answers (3)

Sabaoon Bedar
Sabaoon Bedar

Reputation: 3689

I faced the radio button issue in same way I was trying to make the true and false radio button, when I was clicking on the radio buttons it was not working properly the states were not changing correctly. I solved it with the following way. The below component is functional component keep in mind in class component it won't work.

I made a functional component then using react useState hook I added the state.

  const [autoRegistrationData, setAutoRegistrationData] = useState(
    { invoice_customer:'true' }
  );

then I created the function to handle the change of radio button.

const handleRadioChange = (e) => {

  console.log(e.target.value)
  setAutoRegistrationData({
    ...autoRegistrationData,
    [e.target.name]: e.target.value,
  });
};

and the Last I created my fields for radio button.

 <input
  className="form-check-input"
  type="radio"
  checked={autoRegistrationData.invoice_customer === 'false'}
  value={false}
  name='invoice_customer'
  onChange={(e)=>{handleRadioChange(e)}}
   />

 <input
   class="form-check-input"
   type="radio"
   name='invoice_customer'
   value={true}
   checked={autoRegistrationData.invoice_customer === 'true'}
   onChange={(e)=>{handleRadioChange(e)}}
  />

I didn't focus on designing, this is just an example for those who are stuck in this problem. You can take state of javascript object or simply like this another example:


 const [autoRegistrationData, setAutoRegistrationData] = useState(true);

 const handleRadioChange = (e) => {
  setAutoRegistrationData(e.target.value);
 };

radio buttons :

<input
  className="form-check-input"
  type="radio"
  checked={autoRegistrationData === 'false'}
  value={false}
  onChange={(e)=>{handleRadioChange(e)}}
   />

 <input
   class="form-check-input"
   type="radio"
   value={true}
   checked={autoRegistrationData === 'true'}
   onChange={(e)=>{handleRadioChange(e)}}
  />

Upvotes: 0

Vignesh Kumar
Vignesh Kumar

Reputation: 598

Please use this!

It's working perfectly!

            <label>
                <input type="radio" defaultChecked={true} disabled={false} value={YOUR_Value} />
                {this.state.content}
            </label>

enter image description here

Upvotes: -1

Chris
Chris

Reputation: 59491

You should take a look at the official documentation, specifically the sections regarding Controlled Components and Uncontrolled Components.


Controlled Component

Basically, with controlled components you let React manage the value of said element.

An input form element whose value is controlled by React in this way is called a "controlled component".

To create a controlled component you need a state variable which stores its value, as well as a function which mutates its value based on some event (click, input, etc).

Here's a simple example:

class ControlledComponentDemo extends React.Component {
  constructor() {
    super();
    this.state = {
      input: "",
      radio: null,
      checkbox: []      
    };
  }
  
  changeInput = (e) => {
    this.setState({input: e.target.value});
  }
  
  changeRadio = (id) => {
    this.setState({radio: id});
  }
  
  changeCheckbox = (id) => {
    let arr = this.state.checkbox.slice();
    if(arr.indexOf(id) >= 0) {
      arr.splice(arr.indexOf(id), 1);
    } else {
      arr.push(id);
    }
    this.setState({checkbox: arr});
  }
  
  render() {
    return(
      <form>
        <input type="text" value={this.state.input} onChange={this.changeInput} />
        <br /><br />
        <input type="radio" name="myRadio" checked={this.state.radio === 0} onChange={this.changeRadio.bind(this, 0)} />
        <input type="radio" name="myRadio" checked={this.state.radio === 1} onChange={this.changeRadio.bind(this, 1)} />
        <br /><br />
        <input type="checkbox" name="myCheckbox" checked={this.state.checkbox.indexOf(0) >= 0} onChange={this.changeCheckbox.bind(this, 0)} />
        <input type="checkbox" name="myCheckbox" checked={this.state.checkbox.indexOf(1) >= 0} onChange={this.changeCheckbox.bind(this, 1)} />
      </form>
    );
  }
}

ReactDOM.render(<ControlledComponentDemo />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


Uncontrolled Component

As the name suggests, in uncontrolled components React does not manage the value of the form elements. Instead, these are managed by the DOM directly the "traditional way".

In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

Create an uncontrolled component is easy:

class UncontrolledComponentDemo extends React.Component {
  render() {
    return(
      <form>
        <input type="text" />
        <br /><br />
        <input type="radio" name="myRadio" />
        <input type="radio" name="myRadio" />
        <br /><br />
        <input type="checkbox" name="myCheckbox" />
        <input type="checkbox" name="myCheckbox" />        
      </form>
    );
  }
}

ReactDOM.render(<UncontrolledComponentDemo />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


The issue with your code is that you have a mixed syntax of controlled and uncontrolled components.

In controlled components the value is defined in the state and passed into the value or checked props (depending on the input type) as I demonstrated above.

Since uncontrolled components are not managed by the state we shouldn't pass anything in to the value or checked props either. It doesn't make sense to do that because the DOM manages that on its own.

What we can do though is tell the DOM the initial value of said element. For example a text input could have something already typed in, or a checkbox already checked. We do this with the defaultValue prop.

And this is the mixup that you have done. You are using both defaultValue and checked here. Hence the warning:

Warning: RadioButton contains an input of type radio with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props.

I should also mention that controlled components are the ones recommended by React. You should still read the documentation sections I linked above.

Upvotes: 3

Related Questions