Home > Back-end >  Complete the List component, which accepts an items prop and moves the clicked element to the first
Complete the List component, which accepts an items prop and moves the clicked element to the first

Time:11-14

For example, if the component has the list prop ["A", "B", "C"], the list should look like:

  • A
  • B
  • C

When item B is clicked in the list above, the list should be reordered, resulting in the following order:

  • B
  • A
  • C

const List = (props) => {

  // Yоur cоdе gоеs hеrе

  return  null;

}

document.body.innerHTML = "<div id='root'> </div>";

  
const rootElement = document.getElementById("root");

ReactDOM.render(<List items={["A", "B", "C"]} />, rootElement);


let listItem = document.querySelectorAll("li")[1];

if(listItem) {

  listItem.click();

}

setTimeout(() => console.log(document.getElementById("root").innerHTML));

CodePudding user response:

Try this

import { useState } from "react";

const list = ["A", "B", "C"];

const List = (props) => {
  const [itemList, setItemList] = useState(list);

  const reorderList = (selectedItem) => {
    const restOfTheList = list.filter((item) => selectedItem != item);
    setItemList([selectedItem].concat(restOfTheList));
  };

  return (
    <div>
      {itemList.map((item, itemIndex) => (
        <button key={itemIndex} onClick={() => reorderList(item)}>
          {item}
        </button>
      ))}
    </div>
  );
};

export default List;

Code sandbox => https://codesandbox.io/s/vigorous-kirch-vsqoo?file=/src/App.js:23-639

  • Related