dimanche 30 janvier 2022

React JS - filtering based on multiple checkbox values

I have a simple react application which looks like this:

import { useState } from "react";

const initialState = [
  { id: 1, language: "javascript" },
  { id: 2, language: "java" },
  { id: 3, language: "python" },
  { id: 4, language: "python" },
  { id: 5, language: "javascript" },
  { id: 6, language: "javascript" },
];

function App() {
  const [items, setItems] = useState(initialState);

  const [languages, setLanguages] = useState({
    javascript: false,
    java: false,
    python: false,
  });

  const onChange = (e) => {
    setLanguages({ ...languages, [e.target.value]: e.target.checked });
  };

  return (
    <>
      <div>
        <label>
          <input
            type="checkbox"
            value="javascript"
            name="language"
            checked={languages.javascript}
            onChange={onChange}
          />
          javascript
        </label>

        <label>
          <input
            type="checkbox"
            value="java"
            name="language"
            checked={languages.java}
            onChange={onChange}
          />
          java
        </label>

        <label>
          <input
            type="checkbox"
            value="python"
            name="language"
            checked={languages.python}
            onChange={onChange}
          />
          python
        </label>
      </div>

      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.language}</li>
        ))}
      </ul>
    </>
  );
}

export default App;

I'm now trying to implement filtering but haven't succeeded yet. How can I make displayed items to be filtered and rendered based on all the checked values so each time checkbox values change list items get updated? Please see expected behavior below.

Example 1

State:

const [languages, setLanguages] = useState({
  javascript: true,
  java: false,
  python: false,
});

Output:

<ul>
  <li>javascript</li>
  <li>javascript</li>
  <li>javascript</li>
</ul>

Example 2

State:

const [languages, setLanguages] = useState({
  javascript: true,
  java: false,
  python: true,
});

Output:

<ul>
  <li>javascript</li>
  <li>python</li>
  <li>python</li>
  <li>javascript</li>
  <li>javascript</li>
</ul>



Aucun commentaire:

Enregistrer un commentaire