Search code examples
javascriptreactjsstyled-components

Styling elements individually in mapped array - styled components


I have 4 buttons and each of them has its own correctness check as object prop - isAnswerCorrect.

I have also isCorrect state which i change whenever the button is correct or no.

What i want to achieve?

  • when correct button is clicked, its border color changes to green and rest of the uncorrect buttons borders remain the same
  • when uncorrect button is clicked all the uncorrect buttons change their border color to red and the correct button should change its border color to green

Currently what i have does not have much sense because uncorrect button changes all borders to red and same story with correct button which changes all borders to green. And thats because of that one and only isCorrect state.

How to make it properly with combination of styled components?

Edit fancy-tdd-1gxx5c


Solution

  • You could create a helper function to set the value of isCorrect:

    function isResponseCorrect(isAnswerCorrect) {
        if(isCorrect === undefined) {
          return;
        }
    
        if(isCorrect) {
          return isAnswerCorrect ? true : undefined;
        } else {
          return isAnswerCorrect ? true : false;
        }
      }
    
    return (
        <Wrapper>
          {answerOptions.map((answerOption) => (
            <AnswerButton
              isCorrect={isResponseCorrect(answerOption.isAnswerCorrect)}
              key={answerOption.id}
              onClick={
                () => handleAnswerCorrectness(answerOption.isAnswerCorrect) // TODO
              }
            >
              {answerOption.answerText}
            </AnswerButton>
          ))}
        </Wrapper>
      );
    }
    

    Edit cold-thunder-dec1ud