Home > Enterprise >  changing the order from asc to desc or vice versa on click table header react
changing the order from asc to desc or vice versa on click table header react

Time:06-18

maybe it's simple but I'm not able to understand the solutions I found... I have a ready function that changes the order of the columns when I click on the header, but I would like to make the second click reverse the order.

the function that is working...

  function handleHeaderClick(clickedHeader) {
    const newdata = [...data].sort((a, b) => (a[clickedHeader] > b[clickedHeader] ? 1 : -1));
    setdata((prevdata) => newdata);
  }

what am i trying to do... I also tried doing var and let in the order and it didn't work

@edit 4 Solved Created useState for order Solution...

const [order, setOrder] = useState(true);

  function handleHeaderClick(clickedHeader) {
    setOrder(!order);
    const newdata = props.data.sort((a, b) => {
      const x = a[clickedHeader];
      const y = b[clickedHeader];
      if (order && x > y) return -1;
      return 1;
    });
    props.setdata(newdata);
  }

enter image description here

CodePudding user response:

  function handleHeaderClick(clickedHeader) {
    const order = !order;

react-dom.development.js:4312 Uncaught ReferenceError: Cannot access 'order' before initialization at Object.handleHeaderClick [as onClick]

You're initializing order with the (opposite) of the value of order itself: the error message is self explanatory.

  • Related