Home > Enterprise >  List shifting in React JS
List shifting in React JS

Time:07-15

So basicly what I want is,

I am passing one array in List component like this :

<List items={["A", "B", "C"]} />

Now I need to print each element in list like this :

● A ● B ● C

But whenever someone will click any list element, that element should come at the 1st place. Example : if I clicked B, then output should look like this :

● B ● A ● C

Any solution for this, please help.

CodePudding user response:

you can do something like this

const List = ({items}) => {
  const [list, setList] = useState(items)

  
   return <ul>{list.map((l, i) => 
               <li  
                 onClick={() => setList([l, ...items.filter(item => item !== l)])} 
                 key={i}>
                 {l}
               </li>)}
   </ul>

}


CodePudding user response:

  1. Create a copy of the value you want to move.

  2. Create a copy of your array without the value using filter. or splice if you have the index.

  3. Add the value to the Array copy using unshift

  4. Set your state to the Array copy

Doc : https://love2dev.com/blog/javascript-remove-from-array/ https://www.w3schools.com/jsref/jsref_unshift.asp#:~:text=The unshift() method adds,method overwrites the original array.

CodePudding user response:

   const Home = () => {
    const [myList, setMyList] = useState(["A","B","C"]);


    function shiftPlace(from, to) {
        const arr = myList;
        let cutOut = arr.splice(from, 1)[0];
        arr.splice(to, 0, cutOut);
        setMyList([...arr]);
    }

    return (<div>
        {
            myList.map((v, i) => {
                return <span key={i} onClick={() => {
                    shiftPlace(i, 0);
                }}>{v}</span>;
            })
        }
    </div>);
};

This does everything you need.

  • Related