Home > Software design >  Multiple Background Colors For Buttons In React Quiz App
Multiple Background Colors For Buttons In React Quiz App

Time:10-26

I'm new to learning React and am a bit stumped trying to get over one last hurdle I have in this Quiz App I'm making. I'm having an issue after the users clicks the check their answers, currently I have the selected answer by the user properly displaying as green, but if they answer incorrectly I simply cannot get the user answer to show green and the correct answer to display red. I tried to create a conditional style for it inside the JSX where I am mapping over the answer array and returning a button, but that didn't work (it would color all of them).

Here is the link to a Sandbox I created: https://codesandbox.io/s/laughing-wozniak-qnv6k8?file=/src/Question.js

CodePudding user response:

Here's a start, check how the names are conditionally set on the button and how the css reflects the change; remember the selector order matters.

Your logic around if the right answer is selected seems to work; I didn't check if the answer was correct, but the back color is being applied to all the buttons in the row due to the state being at that level, need to drop it down into the styledButton component itself.

But this is the conditional rendering you were looking for, I think you were trying to set the style conditional to use the selector as a value in the js component? You would have to get the dom element and root var from the css in that case which would be formatted a bit different than a selector; not to mention declare the actual css attribute you want to change in the elements style attribute with double brackets and separated with semi-colons...

But this is likely what you wanted anyway, button class name updates conditionally when prop state is changed and the css selectors update the visual styling based not the new selectors.

https://codesandbox.io/s/summer-sound-jypf9s?file=/src/Question.js

CodePudding user response:

Add the following condition

 ${isFinished && isClicked !== index && index === correctIndex? "red":null}

Below the condition

${isFinished && isClicked === index ? "green" : null}

Here is the link to the updated sandbox - https://codesandbox.io/s/condescending-haslett-5gbbx2

  • Related