1

Here I want to set state the value in setstate as integer in the in my reactjs component. I am unable to do so since the value is not set as integer so in radio button its does not comes as checked.

constructor(props) {
  super(props);
  this.state = {
   frequency: 1,
}
handleSelectChange(event) {

  this.setState({
    frequency: event.target.value
  })
};


<div className = "custom-control custom-radio custom-control-inline"
onChange = {
    this.handleSelectChange.bind(this)
  } >
  <
  input type = "radio"
id = "oneTime"
value = "0"
name = "type"
onChange = {
  event => this.handleSelectChange(event)
}

checked = {
  this.state.frequency === "0"
}
className = "custom-control-input" / >
  <
  label className = "custom-control-label"
htmlFor = "oneTime" > {
    Labels.PRODUCT_SUBSCRIPTION.ONETIME
  } <
  /label> < /
div > <
  div className = "custom-control custom-radio custom-control-inline" >
  <
  input type = "radio"
id = "continuous"
value = "1"
name = "type"
checked = {
  this.state.frequency === "1"
}
onChange = {
  event => this.handleSelectChange(event)
}
className = "custom-control-input" / >
  <
  label className = "custom-control-label"
htmlFor = "continuous" > {
    Labels.PRODUCT_SUBSCRIPTION.CONTINUOUS
  } 
  </label>
  </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

I know we can set this by using defaultValue. But then it becomes uncontrolled which is not encouraged.

2 Answers 2

3

Instead of setting value as string like

<input type="radio" value="1" />

Set it as integer

<input type="radio" value={1} />

Also try to use === while comparing if you want some value of your state to be strictly number, otherwise your comparisons won't be very strict

Edit

To make the radio button checked you can then set the checked attr of radio by comparing it to the value of state

<input type="radio" checked={this.state.frequency === 1} value={1} />
Sign up to request clarification or add additional context in comments.

2 Comments

I tried that earlier but radio button does not get checked when I click on it.
it won't be checked based on value but on checked property, let me edit my answer
0

You should initialize the value like:

<input type="radio"
 checked={this.state.frequency === 1}
 value={this.state.frequency || 0} />

You already noticed from another answer that value="0" will represent the string 0 while value={0} will represent the integer 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.