Why are my radio buttons not toggling state in react?

I’m trying to partially follow the react tutorial.

I’m at this point trying to create a component that has 2 input fields of type “radio”. One is checked by default. I’m trying to mimic a behavior whereby if I click on the other radio button, the currently checked one will be turned off, and the one clicked will be turned on.

The thing is, after I click on the one not initially checked, they both turn off “forever”.

I have debugged by code, and up to the call to setState everything works. The state is set as I want it to be set, but the buttons are not updating.

class App extends React.Component{
  constructor(props){
    super(props)
    this.state = this.createInitialState({celsiusChecked: true})
    this.handleRadioTicked = this.handleRadioTicked.bind(this)
  }

  createInitialState(additionalState={}){
    let state = {
      fahrenheitChecked: false,
      celsiusChecked: false
    }

    state = Object.assign(state, additionalState)

    return state
  }

  handleRadioTicked(event){
    event.preventDefault()

    let radioName = event.target.name
    let stateProperty

    if (radioName === 'c'){
      stateProperty = 'celsiusChecked'
    } else if (radioName === 'f'){
      stateProperty = 'fahrenheitChecked'
    } else {
      throw Exception("something bad happened...probably the input field names have changed")
    }

    let newState = this.createInitialState()
    newState[stateProperty]= true;

    // the newState is calculated OK. Checked for both buttons.
    // Also, initially, the buttons render properly
    this.setState(newState) 
  }

  render(){
    return (
      <div>
          <form>
            <fieldset>
              <input type="radio" name="f" value="fahrenheit" checked={this.state.fahrenheitChecked} onChange={this.handleRadioTicked}/>
              <label htmlFor="f">Fahrenheit</label>
              <input type="radio" name="c" value="celsius" checked={this.state.celsiusChecked} onChange={this.handleRadioTicked}/>
              <label htmlFor="c">Celsius</label>
            </fieldset>
        </form>
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

I am running this example with this codepen setup, which is what facebook provided: http://codepen.io/gaearon/pen/ZpvBNJ?editors=0010

Am I missing anything?

[EDIT] i updated the name of the inputs, and corrected the code. A different issue: Now the inputs NEVER change state. I debugged and the setState method is called with the proper state, however the buttons don’t switch state. I put a breakpoint before the this.setState call, and the buttons looked ok then. They are being switched back to the initial state however after that point somewhere. I should probably try to put a DOM breakpoint of some kind….

The new code:

class App extends React.Component{
  constructor(props){
    super(props)
    this.state = this.createInitialState({celsiusChecked: true})
    this.handleRadioTicked = this.handleRadioTicked.bind(this)

    this.setState = this.setState.bind(this)
  }

  createInitialState(additionalState={}){
    let state = {
      fahrenheitChecked: false,
      celsiusChecked: false
    }

    state = Object.assign(state, additionalState)

    return state
  }

  handleRadioTicked(event){
    event.preventDefault()

    let radioValue = event.target.value
    let stateProperty

    if (radioValue === 'celsius'){
      stateProperty = 'celsiusChecked'
    } else if (radioValue === 'fahrenheit'){
      stateProperty = 'fahrenheitChecked'
    } else {
      throw Exception("something bad happened...probably the input field names have changedx")
    }

    let newState = this.createInitialState()
    newState[stateProperty]= true;

    // Here the newState is succesfully created each time
    // ...still, the radio buttons don't "react" appropriately - pardon the pun
    this.setState(newState) 
  }

  render(){
    return (
      <div>
          <form>
            <fieldset>
              <input type="radio" name="scale" value="fahrenheit" checked={this.state.fahrenheitChecked} onChange={this.handleRadioTicked}/>
              <label htmlFor="f">Fahrenheit</label>
              <input type="radio" name="scale" value="celsius" checked={this.state.celsiusChecked} onChange={this.handleRadioTicked}/>
              <label htmlFor="c">Celsius</label>
            </fieldset>
        </form>
      </div>
    )
  }
}

170 thoughts on “Why are my radio buttons not toggling state in react?”

  1. I was recommended this blog by my cousin. I am not sure whether this post is written by him as
    no one else know such detailed about my problem.
    You’re incredible! Thanks!

    Reply
  2. Greetings! I know this is kind of off topic but I was wondering if you knew where I could
    get a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having problems finding one?

    Thanks a lot!

    Reply
  3. It’s a shame you don’t have a donate button! I’d most certainly donate to this fantastic blog!

    I suppose for now i’ll settle for book-marking and adding your RSS
    feed to my Google account. I look forward to fresh updates and will share this blog
    with my Facebook group. Talk soon!

    Reply
  4. It’s the best time to make some plans for the future and it is time to be happy.
    I’ve read this post and if I could I wish to suggest you few interesting things or suggestions.

    Maybe you could write next articles referring to this article.
    I desire to read even more things about it!

    Reply
  5. Fantastic beat ! I wish to apprentice at the same time as you
    amend your web site, how can i subscribe for a weblog site?

    The account aided me a acceptable deal. I have been tiny bit acquainted of this your broadcast offered shiny transparent concept

    Reply
  6. Have you ever thought about including a little bit more than just your
    articles? I mean, what you say is fundamental
    and everything. But think about if you added some great graphics or video clips to give your posts more, “pop”!
    Your content is excellent but with images and
    clips, this site could undeniably be one of the best in its niche.
    Good blog!

    Reply
  7. When I originally commented I clicked the “Notify me when new comments are added” checkbox
    and now each time a comment is added I get three e-mails with the same
    comment. Is there any way you can remove me from that service?
    Thank you!

    Reply
  8. Hello! This post couldn’t be written any better!
    Reading through this post reminds me of my good old room mate!
    He always kept talking about this. I will forward this write-up to him.
    Pretty sure he will have a good read. Many thanks for sharing!

    Reply
  9. Greetings from Florida! I’m bored to tears at work so I decided to browse your site on my iphone during lunch break.
    I enjoy the knowledge you provide here and can’t wait to
    take a look when I get home. I’m surprised at how quick your blog loaded on my cell
    phone .. I’m not even using WIFI, just 3G .. Anyhow, awesome site!

    Reply
  10. When I initially commented I clicked the “Notify me when new comments are added”
    checkbox and now each time a comment is added I get three emails with the same
    comment. Is there any way you can remove people from that service?
    Bless you!

    Reply

Leave a Comment