2021年5月3日星期一

Can I track multiple checkboxes with React Hooks or do I need to use a Class component?

I'm learning React Hooks and trying to understand how I can manage multiple checkboxes with state. If I only have one checkbox, my code below works - using check as state - but when I have multiple boxes, this doesn't work because onChange = {() => setCheck(!check)} will change the check state for ALL of the boxes at once.

I think it's doable if I use a React class component (something like this.handleCheckboxChange to only change state for the particular checkbox) but I'm trying to see if it's possible to do this with hooks.

import React, { useState } from 'react';    const Search = ({ options }) => {      const [check, setCheck] = useState(false);        const renderedOptions = options.map((option) => {          return (              <div key={option}>                  <label>                      <input                          checked={check ? 'checked' : ''}                          type="checkbox"                          name={option}                          value={option}                          onChange={() => {                              setCheck(!check);                          }}></input>                      {option}                  </label>              </div>          );      });        return (          <form>              <label>Search Engines (check all that apply)</label>              {renderedOptions}          </form>      );  };    export default Search;  
https://stackoverflow.com/questions/67376840/can-i-track-multiple-checkboxes-with-react-hooks-or-do-i-need-to-use-a-class-com May 04, 2021 at 07:06AM

没有评论:

发表评论