Bug when reorder list of React components

4

I have a component that loads a list of components <ComponenteReordenavel> that is rearranged according to the user's taste. The bug happens when I modify the style of this component and reorder again, the style always stays in the component of the position in which it was modified and not in the component that I applied the style .

Debugging

AfterdebuggingtheapplicationIrealizedthattheerrorhappensbecausereactonlyupdatesthecontentswhenIreorderthelist.Ineedtoknowiftheonlywaytosolvethisproblemistomodifythevalueoftheobjectwhenreorderingthelistandwhenrenderingthecomponentagainapplyacertaincssaccordingtoavaluedefinedintheobject.

ReportableComponent

importReact,{Component}from'react';importReactDOMfrom'react-dom';importFontAwesomefrom'react-fontawesome';import{Panel}from'react-bootstrap';importStrongLabelfrom'../StrongLabel/StrongLabel';importPostBetfrom'../PostBet/PostBet';import{Col}from'react-bootstrap';classComponenteReordenavelextendsComponent{constructor(props){super(props);this.state={isRotated:false,chevronStyle:{transform:'rotate(180deg)'}}this.rotateElement=this.rotateElement.bind(this);}componentDidMount(){ReactDOM.findDOMNode(this.refs.chevron).addEventListener('click',this.rotateElement);}componentWillUnmount(){}createPostBet(post,index){return<Colkey={index}xs={6}md={4}><PostBetnameTime={post.name}valueBet={post.value}></PostBet></Col>;}createPostBets(posts){returnposts.map((i,index)=>this.createPostBet(i,index));}rotateElement(){this.setState({isRotated:!this.state.isRotated,});}render(){return(<divclassName="Bet">
        <div className="HeaderBet">
          <FontAwesome style={this.state.isRotated ? this.state.chevronStyle : {} } ref='chevron' name="chevron-down"/>
          <StrongLabel name={this.props.source.description}></StrongLabel>
          <FontAwesome name="arrows-v" onClick={this.props.onClick}/>
        </div>
        <div className="ListBets">
          <Panel collapsible expanded={!this.state.isRotated}>
                {this.createPostBets(this.props.source.bet)}
          </Panel>
        </div>
      </div>
    );
  }
}

export default ComponenteReordenavel;
    
asked by anonymous 08.12.2016 / 18:54

1 answer

1

Two issues that may be responsible for the bug.

You are using the index as key . React uses key to perform its algorithm to update DOM as efficiently as possible.

If you change a position component by changing its key , since the index changes to another, React understands that the first component has changed, but does not understand that it is in the third position now.

The key must always be a unique value and identifier of the resource, regardless of the order in which it is. In your case the post.name itself would be more efficient than the index.

Also do not use ref as a string. It's bad practice. Always use callback.

References:

21.02.2017 / 23:57