Home > OS >  State applies to a group of elements instead of individual
State applies to a group of elements instead of individual

Time:01-16

The idea is: I have 10 buttons, when I click on one button the recognition starts and the color of this button changes, when the recognition stops the button's color changes back to its initial.

But the problem is, when I click on the button, all buttons change its color and when the recognition stops, all 10 buttons change its color back to the initial one.

I keep the state of recognition (true/false) in useState: const [listening, setListening] = useState(false).

Then I map via array of buttons and check if recognition is listening - true otherwise - false:

          <button
            onClick={() => {
              startRec(phrases.transcript)
            }}
          >
            {!listening ? (
              <img src="/recognize_phrase.png" width={40} height={40} />
            ) : (
              <img src="/recognize_phrase_active.png" width={40} height={40} />
            )}
          </button>

CodePudding user response:

You can take another state that stores the index (taken during the mapping array) of the button clicked, so if the id of a button matches with the state it changes its appearance.

<button
        onClick={() => {
            setId(id);
            startRec(phrases.transcript)
        }}
      >
        {(!listening && (idx != id)) ? (
          <img src="/recognize_phrase.png" width={40} height={40} />
        ) : (
          <img src="/recognize_phrase_active.png" width={40} height={40} />
        )}
     </button>

This ensures that the appearance of the button clicked is only changed.

  • Related