When using React.js, clicking on an answer option will change the color of all options, not just the one that was clicked

I'm currently working on my quiz page where all answer options change color when clicked. However, I only want the selected answer option to be colored based on its correctness. The data is being retrieved from a data.json array.

export default function QuizCard({ title, scenario, question, answers }) {
  const [bgColor, setBgColor] = useState('gray')
  function handleAnswerClick(isCorrect) {
    if (isCorrect === true) {
      setBgColor('green')
    } else {
      setBgColor('red')
    }
  }
  return (
    <>
      <Card bgColor={bgColor}>
        <h2>{title}</h2>
        <p>{scenario}</p>
        <h3>{question}</h3>
        <AnswerSection>
          {answers.map((answer => (
            <AnswerButton
              key={index}
              onClick={() => handleAnswerClick(answer.isCorrect)}
              isCorrect={answer.isCorrect}
              bgColor={bgColor}
            >
              {answer.answerText}
            </AnswerButton>
          ))}
        </AnswerSection>
      </Card>

Can anyone guide me on how to highlight only the chosen answer in red or green based on its correctness without affecting the rest of the options?

Your assistance is greatly appreciated, and I apologize for any confusion in my question. I began learning coding just 2 months ago, so I'm still getting familiar with the terminology.

Answer №1

Here's how you can achieve that:

export default function QuizCard({ title, scenario, question, answers }) {
  const [bgColor, setBgColor] = useState('gray')
  const [selectAnswer, setSelectAnswer] = useState(null)
  const handleAnswerClick = (isCorrect, answer) => {
    if (isCorrect === true) {
      setBgColor('green')
    } else {
      setBgColor('red')
    }
    setSelectAnswer(answer)
  }

  return (
    <>
      <Card bgColor={bgColor}>
        <h2>{title}</h2>
        <p>{scenario}</p>
        <h3>{question}</h3>
        <AnswerSection>
          {answers.map(answer => (
            <AnswerButton
              key={answer.answerText}
              onClick={() =>
                handleAnswerClick(answer.isCorrect, answer.answerText)
              }
              isCorrect={answer.isCorrect}
              bgColor={answer.answerText === selectAnswer ? bgColor : 'gray'} // assign bgColor in state only to the right answer and for others use gray as default
            >
              {answer.answerText}
            </AnswerButton>
          ))}
        </AnswerSection>
      </Card>
    </>
  )
}

Answer №2

It is important to note that setting the 'bgColor' for all answer buttons may not be the most efficient approach. Instead, consider modifying the logic to only set the bgColor for the correct answer. This small adjustment should help streamline the process.

export default function QuizCard({ title, scenario, question, answers }) {
  const [bgColor, setBgColor] = useState('gray')
  function handleAnswerClick(isCorrect) {
    if (isCorrect === true) {
      setBgColor('green')
    } else {
      setBgColor('red')
    }
  }
  return (
    <>
      <Card bgColor={bgColor}>
        <h2>{title}</h2>
        <p>{scenario}</p>
        <h3>{question}</h3>
        <AnswerSection>
          {answers.map((answer => (
            <AnswerButton
              key={answer.answerText}
              onClick={() => handleAnswerClick(answer.isCorrect)}
              isCorrect={answer.isCorrect}
              bgColor={answer.isCorrect ? bgColor : 'gray'} // Set bgColor in state only for correct answer, default to gray for others
            >
              {answer.answerText}
            </AnswerButton>
          ))}
        </AnswerSection>
      </Card>

Answer №3

If you want to write more concise code in the function handleAnswerClick, try using this approach:

const handleClick = (correct, answer) => {
  const color = correct ? 'green' : 'red';
  setBackground(color);
  setSelected(answer);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking for a solution to update data in React components after a refresh using databinding and array push

I am dealing with a challenge The webpage is not reacting to the signal consistently. Signals are not coming in regularly. In my scenarios (Array data pushed after refresh) No event is triggered Since I cannot use setState function I believe calling ...

Help Needed: Adding a Simple Element to jQuery Tabs Script

I recently came across a fantastic jQuery tabs script on a website called Tutorialzine. The link to the article can be found here. As I was implementing this script, I realized I needed to customize it by adding specific classes to certain tabs. Specifica ...

AngularJS: Functions may return false due to the asynchronous nature of services

Template Overview: <div data-ng-if="budgetSummaryExists()"> <span>You currently have no budget.</span> <button type="button" class="btn btn-danger" data-ng-click="setRoute('budgets')">Creat ...

Encountering the error "tsx is not defined" during a Jest test in a React/TypeScript project

I'm currently working on implementing Jest tests within a React project that has enforced TypeScript settings. In a simple test.tsx file located in the test folder, I have the following code: import React from 'react'; describe('Test& ...

What is causing the sorting table to fail in React when using useState?

import React, { useState } from "react"; import "./App.css"; const App = () => { const [data, setData] = useState([ { rank: 1, name: "John", age: 29, job: "Web developer", }, { rank: 2, name: "Micha ...

Performing a JSON POST Request: Steps for sending a POST request with JSON data format

I need to send the following data: { "contactsync": { "rev":4, "contacts":[ { "fields": [ { "value": { ...

Ways to combine duplicate entries within a column using Ruby on Rails?

I need some help with a filtering issue related to sign names. I am trying to merge the content together if there is more than one name of the sign. You can refer to the image attached for better clarity, where I have two server names but I only want to di ...

Modifying the structure of serialized data

After serializing a JS form, the data looks like this: .....&xx=xxx&otherError=&input=SMS&message=sdfgs&...... Can anyone provide guidance on how to replace the value of message with the content of a textarea before making an ajax cal ...

Utilize JavaScript to submit the FORM and initiate the 'submit' Event

Hey there! Here's the code I've been working on: HTML : <html> <body> <form enctype="multipart/form-data" method="post" name="image"> <input onchange="test();" ...

An application running on Node.js/Express and hosted on Digital Ocean encounters the "Cannot get /" error message

Despite searching extensively online and sifting through numerous solutions to different scenarios, I remained unable to find a fix that resolved my issue. When attempting to run my server.js file locally, everything operates smoothly. However, upon transf ...

Obtain the data from onTouchTap action

Currently, I have a class that is returning an event to the parent. My goal is to extract the number of the touched button (the label on RaisedButton). Although I am successfully returning the event, I am unable to locate the desired information when I l ...

Sending user input from search component to main App.js in React

I'm currently working on an app that searches a Movies database API. I have a main fetch function in App.js, and in tutorials, people are using a search bar within this main APP component. I'm wondering if it would be better to create a separate ...

"Utilize React Native to access the gallery with the help of an

//I encountered an issue while trying to open the gallery using the react native image picker import React, { useState } from 'react' import { launchCamera, launchImageLibrary } from 'react-native-image-picker' import * as ImagePicker ...

JSON function invocation is failing to load

This is my JavaScript script, When I call the function calculate(), the JSON method ConvertDataTabletoString() only gets called once, when I load the page. I want the method to be called every 5 seconds. I am calling a VB.NET function in .aspx. How can ...

The MDX syntax highlighting feature seems to be malfunctioning in Next.js

After importing the plugin @mapbox/rehype-prism, I noticed that syntax highlighting is not functioning as expected. //next.config.js const rehypePrism = require("@mapbox/rehype-prism"); const withMDX = require("@next/mdx")({ extens ...

Error in TypeScript React: "Could not locate module: Unable to locate 'styled-components'"

Even though I have installed the @types/styled-components package and compiled my Typescript React app, I am consistently encountering this error: Module not found: Can't resolve 'styled-components' I have double-checked that 'style ...

Populate a Material UI Select Component in real-time based on the current state of other components

I'm facing a specific issue at the moment. I am dealing with two select components provided by Material-UI. The first select component includes car brands, while the second one contains car models. Expected behavior Car brands are fetched from the ...

Update the displayed locations on Google Maps by fetching and displaying marker data

I am able to retrieve and display information from my MySQL table, but I need assistance with refreshing this data every 5 seconds using my current code. The data being shown is not extensive, just about 5 or 8 markers at a time. Below is the code I curren ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

Is it possible to incorporate another hue into Material UI's color palette?

I have a unique styleguide that I want to incorporate into Material UI. The Button's color prop currently has these options available: | 'default' | 'inherit' | 'primary' | 'secondary' However, I am in need of ...