Reputation: 13
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.
Upvotes: 0
Views: 202
Reputation: 364
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.
Upvotes: 0
Reputation: 624
Create a copy of the value you want to move.
Create a copy of your array without the value using filter
. or splice
if you have the index.
Add the value to the Array copy using unshift
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%20unshift()%20method%20adds,method%20overwrites%20the%20original%20array.
Upvotes: 0
Reputation: 7129
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>
}
Upvotes: 1