D
D
Denis_81062021-12-15 22:15:05
React
Denis_8106, 2021-12-15 22:15:05

How to end list sort functionality (React)?

Guys, tell me how to finish the functionality of this component, sorting the list.
2 arrays are collected in the component - the 1st array arrives from the Context, the 2nd is a list of 3 icons responsible for sorting the 1st list. The state of the icons arrives as props.
And in general, the functionality works, i.e. not quite, - when you click the icons (one of the three), the corresponding function entry with the number is displayed in the console, but there is no sorting of the list itself yet. Therefore, this question arose.

import React, {useContext, useEffect} from 'react';
import Context from '../context';
import Radium from 'radium';

const ListCompaniesItems = (props) => {
  const styles = {
    li: {
      marginBottom: 10,
      cursor: 'pointer',
      transition: '0.1s',
      
      ':hover': {
        color: '#fff',
      }
    }
  }
  
  const { companyList, toggleStateCompany, toggleTabCompany } = useContext(Context)
  
  const activeIcon = (props.activeIcon);
  
  useEffect(() => {
    (activeIcon === 1) && console.log('функция 1'); //.map(item => (
    (activeIcon === 2) && console.log('функция 2'); //.sort((a, b) => a.name.localeCompare(b.name)).map(item => (
    (activeIcon === 3) && console.log('функция 3'); //.sort((a, b) => a.name.localeCompare(b.name)).reverse().map(item => (
  }, [activeIcon]);
  
  return (
    <ul>
      {companyList.map(item => (
        <li key={item.id} style={styles.li}
          className={toggleStateCompany === item.id ? 'active-menu' : ''}
          onClick={() => toggleTabCompany(item.id)}
        >
          {item.name}
        </li>
      ))}
    </ul>
  );
};

export default Radium (ListCompaniesItems);


Can the code ".map(item => (" be replaced by some variable, in which the required code is passed as a string, so that, under the condition (the code in useEffect), the sorting functionality of the 1st list is replaced? I understand that my idea is adventurous), but maybe somehow you can screw it up to the mind?!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
antsam, 2021-12-16
@antsam

instead of useEffect you need useMemo

const sortedCompanyList = useMemo(
    () => sort(companyList, activeIcon),
    [companyList, activeIcon]
)

It is desirable that the sort(companyList, activeIcon) function return a new array and not mutate companyList.
Yes, and read about memoization and the useMemo hook

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question