MattAttack07 MattAttack07 - 7 months ago 51
Javascript Question

React toggle select field not removing when a specific checkbox is unchecked

I am creating a form in React, there is an option where you can select a State (such as Alabama, Alaska, etc) if a specific select box is checked.

The issue I am having is when unchecking the box, the States select component is not removed.

Input = require('react-bootstrap').Input
States = require('./States.cjsx')

module.exports = InputForm = React.createClass(

propTypes:
state_checkbox: React.PropTypes.bool

getInitialState: ->
{
state_checkbox: false
}

toggleStatesField: ->
console.log('Toggle state changed' + @refs.state_checkbox)
@setState({ state_checkbox: @refs.state_checkbox })

showStatesField: ->
if @refs.state_checkbox
<States />
else
false

render: ->
return(
<Input type="checkbox" ref="state_checkbox" label="Import State?" onChange={@toggleStatesField} value={@state.state_checkbox} />
{ @showStatesField() }
)
)


In the react dev extension, the initial state is set to
false
. When the item is toggled, it then shows
Input{...}
while the state in this object is
null
.

I believe the issue is that the
state_checkbox
returning an object, instead of a boolean. I have searched but cannot find a way to update the state in the
Input{...}
object with
@setState
or changing it to be a boolean with the
propTypes
above.

Answer

You're using @refs.state_checkbox to determine whether the States component should render, but this ref will always be truthy. You probably meant to use @state.

toggleStatesField: ->
  console.log('Toggle state changed' + @refs.state_checkbox)
  @setState({ state_checkbox: @refs.state_checkbox.refs.input.checked })

showStatesField: ->
 if @state.state_checkbox
   <States />
 else
   false