Skip to content Skip to sidebar Skip to footer

Passing A Function To State In React

I am new to React and have a question regarding passing down functions in a state. I have a couple of 'sorting functions' in my util folder, which look like this: export const sort

Solution 1:

1st approach

  • You are putting string into your state. Maybe it's better if you use an object with sort functions and use user input as key to the sorting functions object
const onChangeQueryFilter = (e) => { setQueryFilter(e.target.value); };


const sortingFns = {
  "temp": sortHighestSummerTemp, 
  "hot": sortLargestIncreaseHotDays, 
  "summer": sortColdestSummerCountries, 
  "cold": sortMostColdDays,
   .....
}

const sortedData = sortingFns[queryFilter](data);

2nd Approach

  • It is much better if you pass sorting parameter to your factory of sorting functions.
function sortBy(data, sortKey) {
  return [...data].sort((a, b) => a[key] - b[key])
}

// the query filter should respond to the key on which you should sort the data.
const [queryFilter, setQueryFilter] = React.useState('');
const filteredData = sortBy(data, queryFilter);

Post a Comment for "Passing A Function To State In React"