Modify the color of a div element in React when it is clicked on

My goal is to change the color of each div individually when clicked. However, I am facing an issue where all divs change color at once when only one is clicked. I need help in modifying my code to achieve the desired behavior.

Below is the current implementation:

class Main extends React.PureComponent {
state = {
    color: 'blue',
};
onChange = () => {
    this.setState({color: 'red'});
};
render() {
    return (
        <Box sx={SX.root}>
            <Box sx={SX.page}>
                <Box sx={SX.shapeContainer}>
                    <div
                        style={{backgroundColor: this.state.color, width: 20, height: 20, opacity: '50%'}}
                        onClick={this.onChange}
                    />
                    <div
                        style={{backgroundColor: this.state.color, width: 20, height: 20, opacity: '50%'}}
                        onClick={this.onChange}
                    />
                </Box>
                <MathGrid sx={SX.math1} />
            </Box>

            <Box sx={SX.header} />
            <Box sx={SX.footer} />
        </Box>
    );
}

output

Answer №1

To ensure each div has a unique color, it's important to create separate components for each one with changeable colors. This way, each component will have its own independently managed state rather than sharing the same color state as the rest of the components.

ColorBoxComponent

class ColorBoxComponent extends React.Component {
    state = {
        color: "blue",
    };

    onChange = () => {
        this.setState({ color: "red" });
    };

    render() {
        return (
            <div
                style={{ backgroundColor: this.state.color, width: 20, height: 20, opacity: "50%" }}
                onClick={this.onChange}
            />
        );
    }
}

MainColorComponent

class MainColor extends React.PureComponent {
    render() {
        return (
            <Box sx={SX.root}>
                <Box sx={SX.page}>
                    <Box sx={SX.shapeContainer}>
                        <ColorBoxComponent />
                        <ColorBoxComponent />
                    </Box>
                    <MathGrid sx={SX.math1} />
                </Box>

                <Box sx={SX.header} />
                <Box sx={SX.footer} />
            </Box>
        );
    }
}

Answer №2

To control the color of both divs individually, it's important to manage their color using separate state variables.

Consider adding a new onChange handler or adjusting the existing one to accommodate colors as arguments for customization.

Answer №3

It is important to note that using the same state for both boxes will result in changes being reflected across the entire component. To avoid this, consider creating separate states for each individual box or even isolating each box within its own component.

<div
                        style={{backgroundColor: this.state.color, width: 20, height: 20, opacity: '50%'}}
                        onClick={this.onChange}
                    />
                    <div
                        style={{backgroundColor: this.state.color, width: 20, height: 20, opacity: '50%'}}
                        onClick={this.onChange}
                    />

Answer №4

Make sure to enclose your state variable in backticks like this: ${state.color}.

<div style={{ backgroundColor: state.color , width: 20, height: 20, opacity: "50%" }} onClick={handleClick}></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

What are the steps to create offline documentation for sails.js?

I am looking to integrate offline sails.js documentation into my system. You can find the official documentation for sails.js maintained at this Sails.js Documentation. According to their documentation, they use doc-templater for building the documentati ...

Error message "Unexpected token" occurs when attempting to use JSON.parse on an array generated in PHP

My attempt to AJAX a JSON array is hitting a snag - when I utilize JSON.parse, an error pops up: Uncaught SyntaxError: Unexpected token Take a look at my PHP snippet: $infoJson = array('info' => array()); while($row = mysqli_fetch_array($que ...

I'm encountering an issue with the dropify plugin where the data-allowed-file-

While using the dropify library to style file upload elements in my form, I ran into an issue with the data-allowed-file-extensions parameter not working as expected. Despite specifying allowed file extensions like "png jpg jpeg", the validation for input ...

Convert text into a clickable link

Creating a form with numerous text fields, some of which require numerical input. The main goal is to have users enter a tracking number, order number, or any other type of number that, when submitted, will open a new URL in a separate window with the spec ...

How can I populate a <select> tag with options dynamically using C# when the page loads?

I am using jQuery ajax to populate cascaded dropdown elements from a database. The issue I'm facing is that I can't seem to add the default "Select Program" option at the top of my first dropdown dynamically. Even though I tried using the prepend ...

What is the proper way to generate an iframe with a width set to "100%" or left empty, rather than width = "100"?

I am currently utilizing vimeowrap to iterate through a playlist of videos. I would like the iframe that is generated by vimeowrap to have either a width and height set to "100%" or nothing at all. For more information on Vimeo Wrap, visit: To see my tes ...

Determine the total amount of pages generated from the Twitter search API

Can the Twitter search API provide a count of the pages returned? I'm curious if there is a method to determine how many pages are available for a particular query. ...

How can I execute JavaScript code within Aptana Studio 3 IDE?

After creating a Test.js file, I added two lines of JavaScript code: var x = 5; console.log("The answer is: " + x); The desired output would be: "The answer is: 5" I am curious if there's a way to view this outcome in the Aptana Scripting console, ...

What is the most effective way to transfer color values from one div to another?

When recreating a game similar to Mastermind, I encountered a challenge of copying color values from one div to another upon clicking a button. Despite browsing the web, I haven't found a solution for this specific situation. Below is the code I have ...

Utilizing Material-UI CssBaseline with React JS

Looking to enhance the consistency of my new React app with a sleek design using Material-UI. Want it to be easy to maintain, so decided to start with the default theme. Trying out cssBaseline from Material-UI but running into issues. Not very familiar wit ...

Create custom layouts in NextJS based on the browser URL detection

Trying to implement an optional layout in NextJS, I encountered a problem. I have been trying to find a method to check the browser URL and serve content based on that URL. However, this approach led to server content and browser content becoming different ...

Queueing up file downloads through a web browser

When trying to download multiple files from a server, I am required to queue them up instead of downloading in parallel. Unfortunately, I do not have access to the download server, so my only option is to work with the browser. Is there an API available t ...

Utilizing React refs for interactive tab panels

Currently, I am utilizing React along with material-ui and material-table in my project. One issue I am facing is with a closable tab panel where the corresponding panel components are not unmounted when tabs are switched. Instead, they are just hidden wi ...

Encountering a surprising token error while running a node.js application with a classic example

I downloaded node.js from its official website and followed the instructions provided here. I attempted to run the example code snippet from the "JavaScript - The Good Parts" textbook: var myObject = { value: 0; increment: function (inc) { this.value ...

The Optimal Approach for Importing Libraries across Multiple Files

I have two files - one containing the main code execution, and the other solely consisting of a class. For instance: File_1: const _ = require('underscore'), CoolClass = require('CoolClass'); _.map(//something) Files_2: const _ = ...

Limit the input to numbers when pasting into Angular

Implementing a directive in <input type='text'> to restrict user input to numbers has been successful! The issue arises when a user copies and pastes a string, causing Angular to accept the value and send it to the backend. angular.module ...

Interacting with shadow DOM elements using Selenium's JavaScriptExecutor in Polymer applications

Having trouble accessing the 'shop now' button in the Men's Outerwear section of the website with the given code on Chrome Browser (V51)'s JavaScript console: document.querySelector('shop-app').shadowRoot.querySelector ...

React js axios encountering CORS error while functioning perfectly in postman

I am encountering an issue in my Mern Stack Project where I can successfully create a Lesson using Postman, but when trying from my browser, I get a 500 error in the network tab. The console displays CORS error and another 500 error. I have tried various s ...

Revising HTML content when Angular array is modified

I have a code snippet below where I am updating the value of an object in the first item of an array. However, I'm struggling to find a way to "refresh" the HTML view so that the changes are immediately reflected on the browser. var dataArr ...

What are the steps to achieve such a design?

Can you show me how to create a single layout using HTML and CSS? I am struggling with splitting the screen properly. Could you provide a simple example, maybe on jsfiddle? https://i.stack.imgur.com/d2rbn.jpg Thank you in advance! EDIT: I have added a ...