Search code examples
javascriptreactjscoffeescriptreact-rails

ReactJS: how to use setState to swtich active item


Found mistake by myself, see my answer below

But I would appreciate, if smb explain me how this magic with handling events work. How changeActive function knows what index variable is?

I have list of statements, first of them is active by default. I want to switch active on click.

The code below change Statements` component state activeIndex to the index of clicked statement. But Statement component props active does not react as i assume, it's just disapear from every Statement, so there are no active items in my list.

So what's i've done wrong? And what is a best practice?

statements.coffee

@Statements = React.createClass
  getInitialState: ->
    statements: @props.data.statements
    activeIndex: 0
  changeActive: (index) ->
    @setState activeIndex: index
    console.log(index)
  render: ->
    React.DOM.div
      className: 'row'
      React.DOM.div
        className: 'col-sm-9 statements'
        for statement, index in @state.statements
          React.createElement Statement, statement: statement, index: index, key: statement.id, active: (if @state.activeIndex == index then true), handleActiveStatement: @changeActive

statement.coffee

@Statement = React.createClass
  handleClick: ->
    @props.handleActiveStatement(index: @props.index)
  render: ->
    React.DOM.div
      className: 'statement ' + (if @props.active then 'active ' else null)
      onClick: @handleClick
      @props.index+1+'. '
      React.DOM.span null,
        @props.statement.body

Solution

  • OK, i found mistake. May be it wiil be usefull for smb.

    Error is in this line:

    @props.handleActiveStatement(index: @props.index)
    

    It should be:

    @props.handleActiveStatement(@props.index)
    

    I would appreciate, if smb explain me how this magic with handling events work. How changeActive function knows what index variable is?