Modify only one React Hooks component

Asked

Viewed 336 times

-1

Hello,

I’m running a simple application on Reactjs. I created some check buttons, which when clicked changes color, but I press these buttons on a map and when I click to change the color of one, changes all.

inserir a descrição da imagem aqui

After clicking any button, all are selected.

inserir a descrição da imagem aqui

This is the map function that creates the buttons:

{botoes.map((title, i) => (
            <GridLabel key={i}>
              {check ? (
                <FaCheckCircle
                  onClick={handleUnchecked}
                  size={24}
                  color="#000"
                  style={{ cursor: 'pointer' }}
                />
              ) : (
                <FaRegCheckCircle
                  onClick={handleCheck}
                  size={24}
                  color="#000"
                  style={{ cursor: 'pointer' }}
                />
              )}
            </GridLabel>
          ))}

I created a function to change the state to true, where it changes the color of the button and another to return to false, where the button goes back to the initial state.

 const [check, setCheck] = useState(false);

 function handleCheck(e) {
    e.preventDefault();
    setCheck(true);
  }

  function handleUnchecked(e) {
    e.preventDefault();
    setCheck(false);
  }

From what I’ve researched, I need to store the button being clicked, but I can’t find a way to accomplish this.

  • how you upload this list or are independent boxes ???

1 answer

0

On the map you described you are using check (that theoretically is a Boolean) to iterate.

Use a variable to store the "id" (we can use the index if the positions are never changed) of the selected button.

{lista_de_botoes.map((title, i) => (
        <GridLabel key={i}>
          {checkedId === i ? (
            <FaCheckCircle
              onClick={handleUnchecked}
              size={24}
              color="#000"
              style={{ cursor: 'pointer' }}
            />
          ) : (
            <FaRegCheckCircle
              onClick={(e) => handleCheck(e, id)}
              size={24}
              color="#000"
              style={{ cursor: 'pointer' }}
            />
          )}
        </GridLabel>
    ))}



  const [checkId, setCheck] = useState('');

 function handleCheck(e, id) {
    e.preventDefault();
    setCheck(id);
  }

  function handleUnchecked(e) {
    e.preventDefault();
    setCheck('');
  }
  • The @mcmartin solution, starts from the principle that you want radio check behavior, from a single choice. And as it is not clear in the question, it is a correct form of behavior.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.