Updating previous values in reactjs to a new state

I have a div set up to render multiple times based on data retrieved from the database. The background color of the div corresponds to the ID received from the backend.

My goal is to change the background color of the currently selected div and remove the color from the previously selected div. Here's how I'm attempting to accomplish this:

     constructor(props) {

                super(props);

                this.state = {

                    pollId: this.props.contents.post_poll_content_id,
                    temppollId: this.props.voted_id

                }

     }

     componentDidMount() {

                let el = document.getElementById(this.props.voted_id);

                if (el) {

                    el.style.backgroundColor = "#0b97c4";
                }

     }

     handleClick(id) {

                    this.setState({

                    pollId: id,

                    })

                let el = document.getElementById(this.state.pollId);

                if (el) {

                    el.style.backgroundColor = "#0b97c4";

                }

                let sel = document.getElementById(this.state.temppollId);

                if (sel) {

                    sel.style.backgroundColor = "#FFFFFF";

                }

                this.props.submitvote(vote_object)

       }

       render() {

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

                return (

                    <div className="txt_vote_bar_div" style={{
                        color: voted_id === this.state.pollId ? 'white' : '#9da0a4'
                    }} id={this.state.pollId}>
                        <p className="txt_vote_choice"
                           style={{color: voted_id === this.state.pollId ? '#FFFFFF' : '#6a6a6a'}}
                           id={"id" + this.state.pollId}
                           onClick={() => {
                               this.handleClick(this.state.pollId);

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

I initially set the background color of the div using temppollId when the page loads, and then change the color of the div when clicking on it using pollId.

The issue I'm facing is that this only works once because I am unable to update the last selected div's ID to my temppollId in the handleClick function. How can I ensure that the color of the previously selected div is removed when a new div is selected?

Thank you.

Answer №1

When updating state in React using this.setState(), it's important to pay attention to the parameter prevState. Following React's documentation is crucial to avoid potential bugs and confusion in your code. It's recommended to refrain from directly manipulating the DOM in React, such as using document.getElementById(), unless necessary for specific scenarios like mounting the entire app.

For more information, you can refer to React's documentation on componentDidUpdate. Exploring further into React's documentation overall is also beneficial.

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 modify the numerical values within TimeCircles.js?

I have integrated the TimeCircles.js plugin into a Persian website and need to convert Persian numbers to English. I already have a function that replaces each digit with the appropriate English number. I am able to successfully convert the text inside t ...

Performing API requests at regular intervals

Apologies for the beginner question, I am new to the world of React. I have multiple components where I need to make API calls at intervals to keep the lists updated. In Angular, I used to create a service that would broadcast events at intervals using ...

Preloading error alert message displayed during AJAX request

When I send an ajax request with a dropdown change, the loader div is shown using "before send". However, the issue is that the loader only displays for the first time, even though the ajax functionality works all the time. If you want to check this issue ...

Styling components in React using inline styles that are based on JSON values

I'm successfully pulling in JSON data and mapping it within a React component. However, one of the values in the JSON is a HEX code that I want to apply as an inline style for the background color of a div. I have experimented with various methods, b ...

Guide on implementing react-intl v2 with webpack for loading locale files

Currently, I have successfully set up webpack to manage all my assets. Everything is working as expected. However, I am now looking to incorporate react-intl version 2 to support multiple languages. I have successfully integrated the components from the & ...

What is the best approach for retrieving a User from my Angular front-end service?

INQUIRY: I'm attempting to retrieve the details of the currently logged in user in my Angular 2 frontend service with the following code: UserModel.findById(userID, function (err, user) { It appears that this behavior is achievable from the browse ...

Interactive Table - displays warning message in datatable

Incorporating serverside datatable into my project has been a game-changer. Now, I am trying to enhance the table's responsiveness. I experimented with the code snippet below in conjunction with my existing code. While it did deliver the desired outco ...

How come I am unable to pass JavaScript values to my PHP5 code?

I'm struggling with this code snippet: <?php $html=file_get_contents('testmaker_html.html'); echo $html; ?> <script type="text/javascript"> document.getElementById('save_finaly_TEST').addEventLis ...

Utilizing the controller specified in the template that has been included

Within this snippet of code, I am attempting to utilize a controller named FooCtrl that is defined in the included template app/foo.html, using the directive common.script. angular.module('common.script', []).directive('script', func ...

What causes the shift in the position of the div element?

I have been struggling with a problem in my code. Whenever I hover over this element, it rotates as intended but it also changes its position. I can't figure out why this is happening. Can someone please help me debug this? I would greatly appreciate ...

Utilize a for loop to reference variable names with numbers

Is there a way to extract values from req.body.answerX without manually coding each one using a for loop? I currently have values stored as "answer1, answer2" and so on. This is what I tried: for( var i = 1; i <= 10; i++){ console.log(req. ...

Tips for concealing a tab upon selecting an option from a dropdown menu

<ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#song">Song</a></li> <li id="image-tab"><a href="#image" data-toggle="tab">Image</a></li> </ul> <div class="tab-cont ...

What is the most effective method for verifying a selected item in Jquery UI selectable?

I'm having an issue with my image display div where users can delete selected images. The code functions correctly, but there seems to be unnecessary repetition in certain parts of it. I attempted using `$(".ui-selected").each()` to stop the ...

Python: Change text within HTML content rather than the HTML tags

Looking for help with converting HTML code? <pre class="script">template("main/GlobalShared");</pre> <pre class="script"> var link = '/Draft/Tracker_1.1'; if (wiki.pageexists(link)) { &lt;div class="version"&gt; web ...

Guide on implementing a progress bar for file uploads with JavaScript and AJAX request

I am looking to implement a progress bar in my file uploader. Below is the ajax call I have set up for both file upload and progress tracking. $(function() { $('button[type=button]').click(function(e) { e.preventDefault(); ...

Developing advanced functionalities in React often involves creating custom functions with

When working with a basic component and a custom handleChange() function in App.js, it is important to understand where the parameter 'id' is coming from. While event functions typically receive an event property as an argument, the source of &ap ...

The curious case of jQuery.parseJSON() failing to decode a seemingly valid Json string on a Windows-based server

I am currently running a WordPress JavaScript function code on a Linux server that also includes a PHP function called "get_form_data". jQuery.ajax({ type: "POST", url: MyAjax.ajaxurl, data: {action: "get_fo ...

Highslide's Page Z-Index Elevation

Hey there, I'm currently facing an issue with the z-index positioning of an in-page gallery on my website. I attempted to use the hs.zIndexCounter attribute but unfortunately, it didn't solve the problem. Just so you know, my navigation bar has ...

Managing dependencies in React: how to efficiently use useEffect without redundancy?

Is there a way to remove the dependency on the auth state in a React hook, specifically when using useEffect? I'm looking for a solution that avoids redundancy and the need to create another similar hook. export const useHookAuth = () => { // u ...

What is the best way to combine two JSON objects?

Item A: var item1 = { "roleid": "001", "techid": "001", "role": "WEB DEVELOPER", "tech": "JAVASCRIPT", "experience": [], "certifications": [], "gender": ["Male"], "awards": [], "min_experience_years": "4", "max_expe ...