"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

Creating a dynamic image carousel using jQuery

Today, I completed the jQuery course on Code Academy and am now trying to create an image slider using it. While I have a general idea of how it should work, I feel like I'm missing a key element. My goal is to have the slider continuously running whe ...

Accessing the web3 attribute from the React-Web3 provider to enhance functionality

I'm struggling to understand the basic functionality of react-web3-provider My component structure is as follows: import React, { Component } from "react" import { withWeb3 } from 'react-web3-provider'; import Web3 from 'web ...

Imagine a scenario where your json_encode function returns API data that is already in JSON format. What would

It has been a while since I last worked with JSON/PHP/AJAX, and now I am struggling to access the returned data. The AJAX function calls a PHP script that makes an API call returning JSON in $data. The JSON is then decoded using $newJSON = json_decode($da ...

"What is the best way to connect a md-input to the value of a md-slider

I'm in the process of developing an application using Angular 2.0/meteor, and I'm facing a challenge with binding an input to md-slider. Below is the HTML code for the component: <div class="panel-body"> <form [formGroup]="filtreFor ...

Resolving the ReferenceError in Next.js: How to Handle the localStorage is not defined Issue

After building a React project, I decided to migrate from React Router dom to Next.js. I successfully made the necessary changes and refactored the code in pages/routes and store.js. However, I encountered an error that says "ReferenceError: localStorage i ...

Program that duplicates text to clipboard upon clicking on the text

Hey there, I have a query regarding the script provided below: function copyElementText(id) { var text = document.getElementById(id).innerText; var elem = document.createElement("textarea"); document.body.appendChild(elem); ...

Keep moving forward in Sailsjs even after sending back a response with res.json();

It will keep running even if the condition is met and the code inside return res.json() gets executed. _.each(rooms, function(room){ if(room.users.length == users.length) { return res.json(room); // <-- returns but execution continues } ...

Enabling communication between my React frontend and Express server

I currently have a Digital Ocean Ubuntu VPS set up with Apache, Node, and Mongo running. I can successfully retrieve data from my database using CURL on the server and my node backend is running on port 3000. For my React frontend, I am using Fetch and it ...

Determining the duration since generating a unique objectid in mongodb

I am currently developing an application that offers users the option to reset their passwords. The process is quite straightforward - after entering his email address, the user will receive a link containing the new objectid number. For example: /reset- ...

Creating a Higher Order Component (HOC) with a secure route: A step-by

Currently, I am working with react-router dom v6 and have created a ProtectedRoute component like so: export const ProtectedRoute = ({ children, }: { children: JSX.Element; }) => { let location = useLocation(); const auth = useAuth(); if (! ...

Retrieve custom content from a database using Laravel and Ajax when clicking on a navigation bar

Recently, I've started working with Laravel 7 and AJAX. One of the features I want to implement is a 'product's name' navbar that displays product details in a div without refreshing the page when clicked. I came across a demo showcasin ...

Tips for creating asynchronous Redux actions in a genuine application

Summary: I am looking for an example of an asynchronous redux-thunk action that demonstrates how to make an async call (e.g. fetch) and trigger a state update. Additionally, I want to understand how to chain multiple such actions together, like checking if ...

Tips for extracting information from a Javascript Prompt Box and transferring it to a PHP variable for storage in an SQL database

My current issue involves a specific function I want my script to perform: before a user rejects an entry on the server side, the system needs to prompt a text box asking for the reason behind the rejection. The inputted reason should then be saved to a My ...

What is the best way to simulate a library in jest?

Currently, I am attempting to simulate the file-type library within a jest test scenario. Within my javascript document, this particular library is utilized in the subsequent manner: import * as fileType from 'file-type'; .... const uploadedFil ...

Center the p tag vertically

To ensure the text inside the p tag aligns vertically in the middle, I've set a specific height for the tag. While this works perfectly for single-line text, it shifts to the top of the p tag when there are two lines of text. It's important to k ...

The ng-switch functionality does not seem to be functioning properly, even when the is

My ng-switch is displaying both buttons instead of just one when isActive is false. Can anyone help me figure out what I am doing wrong? <div ng-switch="user.IsActive"> <div ng-switch-when="false"> <button type="button" (click)="activ ...

Determining the height of the tab bar across devices using React-Navigation

How can I position a component right above the TabBar in React-Navigation V2's createBottomTabNavigator? The height of the TabBar appears to vary on different devices, particularly iOS devices. Is there a method to determine and calculate the actual ...

Add the following code snippet below every second set of two paragraphs that are enclosed within h

I am looking to add Advertisements following the 2nd paragraph in every h2 tag. Here is an example of what I want: <h2>Sub title</h2> <p>1st paragraph</p> <p>2nd paragraph</p> <div>INSERTED AD</div> functio ...

The Material-ui toolbar is displaying unexpected results and not showing the desired output

I'm attempting to set up the toolbar using material-ui based on the documentation provided. My toolbar.js file appears as follows: import React from 'react'; import IconMenu from 'material-ui/IconMenu'; import IconButton from &ap ...

Unable to display menu content text using jQuery

Currently experimenting with jQuery to create a dynamic submenu. The goal is to have a sub menu appear when the main menu is clicked, and then disappear when an item in the sub menu is selected, revealing additional information within a div. Unfortunately, ...