Home > Blockchain >  FIlter and unfilter button in react native
FIlter and unfilter button in react native

Time:12-04

I'm trying to filter some data by their category id. Right now I can filter by category with value: 1. What I am trying to achieve is when the button is clicked again, it should clear the filter. Here is the code below:

const onPress = () => {
    const filteredResults = results.filter((result) =>{
        return result.category === 1;
    });
    setResults(filteredResults);
};

The button:

<Button onPress={() =>{onPress()}}>Lajme</Button>

How can I implement this function in the same button:

const clearFilter = () => {
    const filteredResults = results
    setResults(filteredResults);
};

CodePudding user response:

Store the current filter (category) with useState(), and whenever you update it (see toggleFilter) check if the current filter is already set. If it is, reset (change to null for example).

const { useState, useMemo } = React;

const Demo = ({ results }) => {
  const [category, setCategory] = useState(null);
  
  const filteredResults = useMemo(() => results.filter(result => category === null || result.category === category), [results, category]);
  
  const toggleFilter = cat => setCategory(c => cat === c ? null : cat);

  return (
    <div>
      <button onClick={() => toggleFilter(1)}>Cat 1</button>
      <button onClick={() => toggleFilter(2)}>Cat 2</button>
      
      <div>
        {JSON.stringify(filteredResults)}
      </div>
    </div>
  );
};

const results = [{ category: 1 }, { category: 2 }, { category: 2 }, { category: 1 }]

ReactDOM.render(
  <Demo results={results} />,
  root
)
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Basically, you can use a state variable to know if the filter is currently applied or not.

const [isFiltered, setFiltered] = useState(false);

const onPress = () => {
    if (isFiltered) {
        setResults(results); // Update results without filter
        setFiltered(false); // Update the state
    } else {
        const filteredResults = results.filter(({ category }) => category === 1); // Filter the results
        setResults(filteredResults); // Update results
        setFiltered(true); // Update the state
    }
};

// ...

<Button onPress={onPress}>Lajme</Button>
  • Related