"Is there a way to modify the color of the button once it's been clicked, but only for the specific button that was

Looking to create a Quiz App using React and facing an issue where all buttons change color when clicked, instead of just the one that was clicked. Any solutions on how to make only the clicked button change its color in React.js?

App.js

import Main from './Main'
import Quiz from './Quiz'
import { useState } from 'react'

export default function App() {

    const [switch1, setSwitch1] = useState(false)
    const [color , setColor] = useState(false)

    const qanda = [

        {
            "question": "In web design, what does CSS stand for?",
            "answerOptions" : [ {"answerText" : "Cascading Style Sheet" , "correctAns" : "true" , "id":1 } ,
                                {"answerText" : "Counter Strike: Source" , "correctAns" : "false" , "id":2 } ,
                                {"answerText" : "Corrective Style Sheet" , "correctAns" : "flase" , "id":3 } ,
                                {"answerText" : "Computer Style Sheet" , "correctAns" : "false"  , "id":4 } ]
        },
    
    
        {
            "question": "Under what pseudonym did Stephen King publish five novels between 1977 and 1984?",
            "answerOptions" : [ {"answerText" : "Mark Twain" , "correctAns" : "false" , "id":5} ,
                                {"answerText" : "Richard Bachman" , "correctAns" : "true"  , "id":6} ,
                                {"answerText" : "J. D. Robb" , "correctAns" : "false"  , "id":7} ,
                                {"answerText" : "Lewis Carroll" , "correctAns" : "false"  , "id":8} ]
        },
    
        {
            "question": "Which modern day country is the region that was known as Phrygia in ancient times?",
            "answerOptions" : [ {"answerText" : "Greece" , "correctAns" : "false"  , "id":9} ,
                                {"answerText" : "Syria" , "correctAns" : "false"  , "id":10} ,
                                {"answerText" : "Egypt" , "correctAns" : "false" , "id":11 } ,
                                {"answerText" : "Turkey" , "correctAns" : "true"  , "id":12} ]
        },       
    ]

    const quizQ = qanda.map(ques => <Quiz question={ques.question} answer1={ques.answerOptions[0].answerText}  answer2={ques.answerOptions[1].answerText}  
        answer3={ques.answerOptions[2].answerText}  answer4={ques.answerOptions[3].answerText} click={switchColor} clicked={color}  />)

   
 
    function switchIt() {
        setSwitch1(prevValue => !prevValue)
    }

    function switchColor() {
        setColor(prevValue => !prevValue)        
    }


    return (
        <div className="body">
            {switch1 ? quizQ  : <Main onclick={switchIt}/> }
        </div>
    )
}
...

I am sorry if I have done the techniques wrong this is my first project after learning React

Answer №1

If you're looking to manage color using state, one approach could be storing the color in a React component's state. Here's an example that might help you with the issue:

class ColorButton extends React.Component {
constructor(){
    super();

    this.state = {
       black: true
    }
}

changeColor(){
   this.setState({black: !this.state.black})
}

render(){
    let buttonClass = this.state.black ? "blackButton" : "whiteButton";

    return (
         <button className={buttonClass} onClick=. 
 {this.changeColor.bind(this)}>
              Change Color
         </button>
    )
 }
}

React.render(<ColorButton />, document.getElementById('color-container'));

You can check out the live example here: https://jsfiddle.net/tkkqx2y2/

Big thanks to @user3350597 for sharing their insights!

Answer №2

import React, { useState } from "react";
import "./App.css";
const App = () => {
  const [style, setStyle] = useState(true);

  const changeStyle = () => {
    setStyle(!style);
  };
  return (
      <div className={style ? "cont" : "cont2"}>
        <button className="button" onClick={changeStyle}>
          Click me!
        </button>
      </div>
  );
};
export default App;
.cont {
  width: 250px;
  height: 250px;
  margin-top: 50px;
  margin-left: 150px;
  background-color: violet;
}
.cont2 {
  width: 250px;
  height: 250px;
  margin-top: 50px;
  margin-left: 150px;
  background-color: yellow;
}

Answer №3

One possible approach is:

import "./styles.css";
import "./App.css";
import { useState } from "react";

export default function App() {
  const [active, setActive] = useState(null);
  const handler = (i) => {
    setActive(i);
  };

  const btns = [
    { id: 0, title: "First Button" },
    { id: 1, title: "Second Button" },
    { id: 2, title: "Third Button" }
  ];

  return (
    <div className="App">
      {btns.map((btn, i) => (
        <button
          key={i}
          className={i === active ? "active-btn" : "inactive-btn"}
          onClick={() => handler(i)}
        >
          {btn.title}
        </button>
      ))}
    </div>
  );
}

.inactive-btn {
  border: none;
  padding: 8px;
  border-radius: 12px;
  color: white;
  background: grey;
}
.active-btn {
  color: white;
  border: none;
  padding: 8px;
  border-radius: 12px;
  background: black;
}

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

Validating a string using regular expressions in JavaScript

Input needed: A string that specifies the range of ZIP codes the user intends to use. Examples: If the user wants to use all zip codes from 1000 to 1200: They should enter 1000:1200 If they want to use only ZIP codes 1000 and 1200: They should enter ...

Cypress OPENSSL_internal:NO_START_LINE error detected

Has anyone encountered this error before? I've already tried clearing the cypress cache and reinstalling it, but the error persists. I couldn't find a solution to resolve this issue. The version I am using is 6.5.0. Error: error:0900006e:PEM rou ...

Navigating to a Different Page in React with a Button and Link

When I try to navigate to another page using a button, the pages don't change at all. I am currently using Link and Router from Router-DOM. Below is the code snippet I am using: <Link to="/page2"> <button type="button" price={data.item}& ...

Modify a particular row in a table by referencing its distinct identifier

Currently, I have two components within my ReactJS application - the parent component is named Layout and the child component is called Report. In the Report component, there is a table that loops through and displays a list of car accidents. There is a ha ...

Include a single element repeatedly on a single webpage

Is there a way to add the same component multiple times on one page? I have an input component that receives props and performs certain functions. I need to include more than one instance of this input component on a single page, but when I try to copy and ...

Tips for locating the existence of an Azure File in NodeJS

Currently, my project involves utilizing azure file storage along with express JS for creating a backend to display the contents stored in the azure file storage. The code I am working on is referencing this documentation: https://learn.microsoft.com/en-u ...

MaterialUI's Tooltip component is causing warning messages to appear on the client's console

Issues with MaterialUI Tooltip causing warnings in client console "Failed prop type". However, the mentioned props are not used in my components. Warnings displayed on client console: Warning: Failed prop type: The following properties are not supported: ...

The Node.js application is up and running on the Node server, but unfortunately, no output is

Greetings, I am a beginner in nodejs. var io = require('socket.io').listen(server); users = []; connections = []; server.listen(process.env.PORT || 3000); console.log('server running....on Pro'); app.get ('/', function(re ...

The button's color remains static in Internet Explorer despite attempts to change it using a linear gradient background image

I'm curious why the button appears grey in IE and turns blue on hover, rather than starting off blue and becoming darker blue when hovered over. I've managed to make it work in other browsers, but I'm struggling with the code for IE. Thank ...

Get rid of the arrow that is displayed when using the `time` input type in HTML5

Recently, I encountered an issue with the default HTML5 code snippet. My custom background looked perfect except for a pesky black arrow appearing on the right side. In this image, you can see the problematic black arrow that needs to be removed. I attemp ...

Customizing pressed row styles and properties within a map iteration in React Native

How can I modify the style of a single item in a list when a button is pressed in React-Native? I want only the pressed item to change, not the entire row. Here is my attempt at implementing this: //hooks const [activeStyle, setActiveStyle] = useState( ...

Is it possible to selectively subscribe to specific parts of a state in Zustand?

Currently, I have been utilizing a method where I subscribe the state of a component to a store in order to update it once a specific function has finished executing. This process involves: useAirQualityStore.getState().updateAirQuality(); ... this.state ...

Why isn't the background of the container div at the top when using multiple CSS sheets?

I am revitalizing a dull website and seeking feedback on my template design here: Check out the ideal look It's quite lovely! However, as I attempt to incorporate my background, menu, and footer elements, I seem to be experiencing issues with my con ...

Unable to find the designated ./uploads directory while attempting to upload a file in Express JS

I'm currently working on a project with the following structure: -app -uploads -client - dropzone.js -server.js My goal is to upload a file using dropzone js, Express JS, and React JS. However, whenever I try to drop a file in ...

guide on creating a simple line highchart using JSON data

Here is the JSON data I have: {"09/02/2014 15:36:25":[33.82,33.42,40.83],"08/11/2014 16:25:15":[36.6,33.42,40.45],"07/30/2014 08:43:57":[0.0,0.0,0.0],"08/12/2014 22:00:52":[77.99,74.1,80.12],"08/12/2014 21:19:48":[56.91,63.23,52.42],"07/23/2014 13:37:46": ...

Closing the space between navigation bar choices

I'm currently working on my website's navbar menu and struggling to eliminate the gap between each of the navbar links. It seems that the li attributes with the class dropdown are slightly wider than the rest of the links, causing this issue. I&a ...

Guide on implementing gradient animation effects in a React component

How can I implement gradient animation effects like this example in a React component using inline CSS? I need to utilize the CSS-based gradient animation effects shown below directly within the React component. Are there any specific packages available ...

Managing jQuery Dependency in Node Package

I am facing an issue while trying to implement the 'jvectormap' package in Node, as it has a dependency on jQuery. My query is fairly straightforward. Whenever I attempt to import jVectorMap, I encounter the following error: Uncaught ReferenceE ...

Dividing an array in PHP using Ajax

Hey there, I have successfully sent data from PHP to Ajax using Json but now I need help in splitting the response. Can anyone guide me on how to alert each element separately? $.ajax({ url:"myHandler.php", type:"POST", ...

Built-in functionality to easily customize gradients within material-ui themes

If we want to customize the theme in material-ui, we can do so by following these steps. import { createMuiTheme } from '@material-ui/core/styles'; const theme = createMuiTheme({ palette: { primary: { main: '#ff4400' } ...