Home > Software engineering >  How to move the list item to top when selected in ReactJs
How to move the list item to top when selected in ReactJs

Time:07-25

I'm trying the scenario in the ReactJS application like. created dummy data in App.js itself with name and id, crated another component with List.js where displaying the list items.

If I selected any of the list item it should be move the item to top like below before

  • A
  • B
  • C

after

  • B
  • A
  • C

I created function in List.js file but it not working

//----App.js-------
import "./styles.css";
import List from './List'

const data = [
  {id:1,letter:"A"},
  {id:2,letter:"B"},
  {id:3,letter:"C"},
]
export default function App() {
  
  
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <List items={data}/>
    </div>
  );
}


//----List.js-------
import React from 'react';
import {useState} from 'react'

export default function List({items}){
  console.log(items);
  const [selectedIndex,setSelectedIndex] = useState(0)

  const selectList = (items,ind)=>{
    console.log(ind 1);
    
    const arr = Object.entries(items,ind)
    setSelectedIndex(()=>{
      arr.sort((a,b)=>{
        return a.id===ind 1?-1:b.id===ind 1?1:0
      })
    })
    // console.log(items,ind);
    
  }
  
  return(
    <div>
      <ul>
        {/* {console.log(items)} */}
        {items.map((item,ind)=>{
          return(
            <li key={ind} onClick={()=>selectList(item,ind)}>{item.letter}</li>
          )
        })}
      </ul>
    </div>
  )
}

CodePudding user response:

Since you need to update the order of the items, it's better to have items as a state property.
To initialize state with props, getDerviedStateFromProps should be used.

class List extends Component {

    constructor(props) {
        super(props);
        this.state = {selectedIndex: 0, items: []};
    }

    static getDerivedStateFromProps(props, state) {
        return {items: props.items};
    }

    selectListItem=(id,ind)=> {
        this.setState((state,props)=> {
            let excludingSelected = state.items.filter((itm,i)=> ind != i);
            return {
                items: [state.items[ind]].concat(excludingSelected), 
                selectedIndex: ind
            };
        }
    }
}

Prefer id as key to index (Edit silly-grass-gsj34d

  • Related