Search code examples
reactjsreorderlist

Reordering list element in react js


I am wondering how to re order a list element. Its like you have a list of an elements li and put the last element in the first place like the index of 10th would be placed in the index of 0

React.render(   <div>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li> //When an event fires, this item would go up to the first index   </div>,   document.getElementById('example') );

Solution

  • Based on your comment on Abdennour answer (you need to update an item regardless of its position), you cannot do such operation with an array of simple numbers, you need to index your values:

    class MyList extends Component {
    
      render() {
        return(
          <ul>
             {this.props.items.map((item ,key) => 
                 <li key={key}> {item}</li>
              )}
          </ul>
        )
      }
    
    }
    
    
    class App extends React.Component{
    
        constructor(props) {
          this.state= {
            listItems: [{id: 1, val: '1'}, {id: 2, val: '2'}, {id: 2, val: '2'}, {id: 3, val: '3'}]
          };
        }
    
        reverse = () => {
           this.setState({
             listItems: this.state.listItems.reverse()
           });
        }
    
        // You can ignore this, simple put some random value somewhere
        // In your case this would be the function that changes the value of one of the items, should of course be NOT random
        changeRandom = () => {
          const index = Math.floor(Math.random() * this.state.listItems.length);
          const newList = this.state.listItems.slice();
          newList[index] = Math.floor(Math.random() * 10).toString();
    
          this.setState({
            listItems: newList
          })
        }
    
        render() {
          return (
            <div>
              <div>
                 <MyList items={this.state.listItems.map(item => item.val)} />
              </div>
              <div> 
                 <button onClick={reverse}>Reverse</button>
              </div>
              <div> 
                 <button onClick={changeRandom}>Random Change</button>
              </div>
    
            </div>
    
           )
        }
    }