Styling just a single div when the state changes

I have a scenario where I am rendering 4 divs based on data fetched from my backend. Each div is colored according to a state change. While I have successfully implemented this, the issue is that all 4 divs can be colored in this way simultaneously. I want to ensure that only one div is colored at a time - when I color a new div, the previous one should revert back to its original color. How can I achieve this functionality?

Here is a snippet of my code:

textVote() {

        this.setState({
            vote_status: !this.state.vote_status
        })

    }

handleClick(id) {

        let vote_object = {
            voting_object: id,
            post_id: this.props.postId
        }
        this.props.submitvote(vote_object)
        this.textVote();

    }


render() {

        console.log("getVoteStatus", this.props.getVoteStatus)

        let {contents, submitvote, postId} = this.props

return (

        <div className="txt_vote_bar_div" style={{backgroundColor: this.state.vote_status ? '#0b97c4' : 'white'}}>
           <p className="txt_vote_choice" style={{color: this.state.vote_status ? '#FFFFFF' : '#6a6a6a'}}
               id={contents.post_poll_content_id} onClick={() => {

                     this.handleClick(contents.post_poll_content_id);

                  }}> {contents.content} </p>
            <p className="txt_tot_votes" style={{color: this.state.vote_status ? '#FFFFFF' : '#6a6a6a'}}> 56% (Votes: {contents.votes}) </p>
        </div>
   );
    };

Is there a way for me to ensure that only one div background is colored at a time and remove the background color when another div is selected? Thank you.

Answer №1

It seems like your goal is to create multiple div elements that change color when clicked, with only one div being highlighted at a time. Is my understanding correct?

One approach to achieve this could involve assigning a unique number to each component.

handleClick = (number) =>{
  this.setState({
      vote_status: number
  })
}

render() {
  {data.map((content,index) => {
    <div
      style={{backgroundColor: this.state.vote_status === index ? '#0b97c4' : 'white'}}
      onClick={() => {this.handleClick(index)}}>
    </div>
  })}
}

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

Is it possible to render array items into separate divs using the .map() method without displaying commas?

After extensive searching, I have only come across solutions that involve using .join() to combine the items into a single string. const createCard = () => { const pokemonTypes = ['grass', 'fire', 'water']; return ...

When zooming in or out on a mobile device, an unusual white line appears

Encountering a strange white gap on mobile devices when zooming in or out. This issue seems to be related to the use of background-color on sections. Strangely, the problem only occurs on mobile devices while zooming in, but does not appear on normal deskt ...

PHP form submission upon conditions being satisfied

I am not utilizing Javascript as it is disabled in my current environment. Here is the code that I would like you to review. I am attempting to use PHP to replicate the functionality of Javascript or jQuery's simple : document.form2.submit() <div ...

Excessive alerts being produced within the loop

I am trying to remove a wine from a JSON wine list and I want to display an alert if the wine doesn't exist in the JSON file. However, the alert is popping up for every entry in the list. I am struggling to find a way to use an if statement before pro ...

Retrieving a variable in a JavaScript function while a webpage is in the process of loading

Recently, I was working on writing Selenium test cases in C# and encountered an issue while trying to capture a value from a webpage. The problem arose when the retrieved value was rounded to 5 decimal points which was not what I wanted. Instead, I needed ...

Determining the optimal time to utilize the addClass function in jQuery and CSS

One of my HTML elements has the class "article": <article> Content </article> In my jQuery script, I want to add specific classes that have been predefined: $('article').addClass('rounded box-shadow gradient-bright'); I ...

Using default language in Next.js internationalization: a step-by-step guide

I've been immersing myself in the Nextjs internationalization documentation for the past two days. My goal is to have support for two languages: en, fa. I also want to be able to switch between them with URLs structured like this: https://example.com ...

Top reasons to choose makeStyles over inline styles in Material-UI

Material-UI provides the makeStyles function for custom CSS styling. Should one use it if a theme is not being utilized in that specific CSS? For instance: import React from "react"; import { TextField, Paper, Button, Box } from "@material-ui/core"; co ...

Passing a Javascript variable to the NAME attribute of an HTML <a href> tag: Steps to do it efficiently

I need assistance with passing a JavaScript variable to the NAME attribute of an HTML tag. Let's consider this script example: <script> var name = "Click here!"; </script> My goal is to pass the variable to some code in order for <a ...

Is there a way to incorporate an array into an array of arrays with jQuery?

I am working with an array shown below: var cString = [ ['1','Techdirt','www.techdirt.com'], ['2','Slashdot','slashdot.org'], ['3','Wired&apos ...

AngularJS fetches the 'compiled HTML'

If I have this angularjs DOM structure <div ng-init="isRed = true" ng-class="{'red': isRed == true, 'black': isRed == false}"> ... content </div> How can I obtain the 'compiled' version of this on a cl ...

Having trouble loading select fields using AJAX within Wordpress? Update and find a solution!

UPDATE: I am struggling to iterate through the response object and populate a select field using my ajax function. Although I have tried using a for loop instead of each(), the select field gets populated with "undefined". Any suggestions on how to resolve ...

Achieve identical outcomes with PHP's `strlen` function and jQuery's `val().length` method

Currently, I am utilizing jQuery to dynamically count the value of a textarea: function count_chars () { count_chars=$('#text_textarea').val().length; } Upon submission, I serialize the form and send the textarea text via AJAX to a PHP file ...

Display or conceal div based on chosen options

I am working on a feature that involves three dropdown select boxes, each containing different sets of demographic attributes. My goal is to show a score based on the combination of selections made by the user. For example, if a user chooses Male, 18-24, A ...

Having trouble with Vue.js implementation of Bootstrap tab navigation?

I am currently working on a vue.js application that consists of 2 routed components. I recently attempted to integrate a bootstrap tab navigation into the first component, but unfortunately, the tab contents are not being properly displayed. <templat ...

What is the best way to interpret NPM dependency conflict errors?

Running npm install on an outdated project has led to NPM dependency errors. While I've encountered similar issues in the past, I've struggled to find a comprehensive guide on interpreting these errors. A forum thread comes close, but doesn' ...

waiting for a task to be carried out

Currently, I am working with a function called doSomething() which can be triggered by various DOM events. Is it feasible to listen not just for an event, but for the exact moment when this function is executed? To clarify - I am unable to modify the orig ...

Looking to parse and iterate over JSON data retrieved from a query using Express and Jade?

As a newcomer to nodejs, I am facing an issue with passing JSON data from a select query to the Jade view. Using Node.js Tools for Visual Studio and Express + Jade in my project, here is a snippet from my index.js file: exports.products = function (req, r ...

What steps should I take to stop material-ui Select options from opening when clicking on specific parts of the selected option?

Presently, I am utilizing a Select component from @material-ui/core/Select, which contains only one option for simplification purposes, and the code snippet is as follows: <FormControl> <InputLabel id="demo-controlled-open-select-label">Test ...

What is the best approach to incorporate this feature in a React application?

I am planning to create a webzine website using React. I am looking to achieve the functionality where clicking on the index button will enlarge the box size and reveal a hidden menu bar, similar to the images below. https://i.stack.imgur.com/S4kUg.png ...