Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

react filter array

import { useState } from "react"
2
3let numbers = [64, 84, 22, 32, 83, 65, 51, 26, 23, 56]
4function App() {
5  const [filteredNumbers, setFilteredNumbers] = useState(numbers)
6
7  const radioChangeHandler = e => {
8    const value = e.target.value
9    if (value === "even") {
10      setFilteredNumbers(
11        numbers.filter(number => {
12          if (number % 2 === 0) {
13            return true
14          }
15          return false
16        })
17      )
18    } else {
19      setFilteredNumbers(
20        numbers.filter(number => {
21          if (number % 2 !== 0) {
22            return true
23          }
24          return false
25        })
26      )
27    }
28  }
29
30  return (
31    <div className="App">
32      <h2>Number filtering</h2>
33      <input
34        type="radio"
35        name="evenOrOdd"
36        id="even"
37        value="even"
38        onChange={radioChangeHandler}
39      />
40      <label htmlFor="even">Even</label>
41      <input
42        type="radio"
43        name="evenOrOdd"
44        id="odd"
45        value="odd"
46        onChange={radioChangeHandler}
47      />
48      <label htmlFor="odd">Odd</label>
49      <ul>
50        {filteredNumbers.map(number => {
51          return <li key={number}>{number} </li>
52        })}
53      </ul>
54    </div>
55  )
56}
57
58export default App
Source by www.codingdeft.com #
 
PREVIOUS NEXT
Tagged: #react #filter #array
ADD COMMENT
Topic
Name
6+3 =