Styling a <td> tag with ReactJS in an array context: Tips and tricks

I am currently working on a React component called Table, which displays a table based on the elements in an array prop. One specific requirement I have is that when a user clicks on a button, the column with the id foo should change its background color to yellow.

class Table extends React.Component {
  render() {
    return (
      <table>
          <thead>
            <tr><th>Heading 1</th></tr>
          </thead>
          <tbody>
            {this.props.array.map(element =>
              <tr key={element}>
                <td id="foo">{element}</td>
              </tr>
            )}
          </tbody>
      </table>
    );
  }
}

Currently, my approach involves using another React component:

class Bar extends React.Component {
  row;

  componentDidMount() {
    this.row = document.getElementById("foo");
  }

  render() {
    return {
      <button onClick={(event) => {
        this.update();
      }}>I will turn the #foo column yellow!
      </button>
    }
  }

  update() {
    this.row.classList.add('yellow-color');
  }
}

CSS:

.yellow-color {
  background-color: yellow;
}

However, it seems that my current implementation does not achieve the desired effect. Can anyone provide guidance on why this may be happening and how to address this issue effectively? Your insights would be greatly appreciated!

Answer №1

Avoid using document.getElementById() in React as it is not recommended. Instead, consider utilizing Refs for similar functionality.

You can also achieve the same outcome by utilizing state and passing props:

class Table extends React.Component {
  state = {
    color: "black"
  };
  update = () => {
    this.setState({
      color: "yellow"
    })
  }
  render() {
    return (
      <div>
      <button onClick={(event) => {
        this.update();
      }}>I will turn the #foo column yellow!
      </button>
      <table>
          <thead>
            <tr><th>Heading 1</th></tr>
          </thead>
          <tbody>
            {this.props.array.map(element =>
              <tr key={element}>
                <td style={{ backgroundColor: this.state.color }}>
                  {element}
                </td>
              </tr>
            )}
          </tbody>
      </table>
      </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

Different ways to display a static content list using Vue's named slots

I'm struggling to make the following setup work: My parent template <comp> <a href="#" slot="links">link 1</a> <a href="#" slot="links">link 2</a> </comp> and in my comp ...

Creating interactive and visually appealing websites using a combination of JavaScript, PHP, and

I'm looking for a software that caters to all my website design needs, supporting various web languages such as HTML, CSS, PHP, JavaScript, and the Laravel framework. I also need it to assist with database management and interface design from start to ...

Using AJAX to assign PHP session variables

Is there a way to update the SESSION variable named "fullname" on Page 2 without causing the page to refresh? This is my attempt using AJAX: HTML code for Page 1: <input type="text" name="fullname" id="fullname" placeholder="Full name"> <butto ...

"Android Webview's evaluateJavascript function is not returning the expected value

I am attempting to retrieve the username from a webview, but it is returning a null object. webView.settings.javaScriptEnabled = true webView.evaluateJavascript( "(function() { return document.getElementsByClassName('lgn-loginname') })() ...

How to access the public folder in React from the server directory

I am having an issue with uploading an image to the react public folder using multer in NodeJs. Everything was working fine during development, but once I deployed it, the upload function stopped working. It seems like the multer is unable to reference or ...

Example of a chat server code using NodeJS

I'm looking to add a chat module to my web application. After searching on , I found several chat modules but none of them have clear examples on how to implement them in my project. Can someone share a tutorial that is based on existing NodeJS modul ...

The collapsible tree nodes overlap one another in the D3.js visualization

I'm currently working on integrating a d3 code into Power BI for creating a collapsible tree structure. Each node in the tree is represented by a rectangular box, but I've run into an issue where nodes overlap when their size is large. Below is t ...

Encountering a parsing error with JSON - Type mismatch detected

I have a sample JSON data that looks like this: { "findItemsByKeywordsResponse":[ { "ack":[ "Success" ], "version":[ "1.13.0" ], "timestamp":[ "2015-02-10T18:12:21.785Z" ], "searchResult":[ ...

An efficient method for duplicating HTML content with varying values

Creating a webapp using Google Script requires displaying a list of ideas including title, description, initiator, and status. This information is stored in an array called "ideas". In the Index file, there is a table structure: <table> <the ...

The Cross-Origin Request has been blocked due to the Same Origin Policy prohibiting access to the remote resource. The reason for this is that the CORS preflight response was unsuccessful

SERVERSIDE // Establishing Headers app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE"); res.header("Access-Control-Allow-Headers ...

Tips on boosting CSS specificity in Material-UI's makeStyle for styled components in order to successfully override the root style

As a newcomer in the world of React, I am attempting to utilize MUI makeStyles to customize the existing styles. However, I have encountered an issue where setting fontWeight to 'bold' does not seem to work, even when using !important. Any sugges ...

Unable to retrieve value from a hidden input field using JavaScript

My goal is to retrieve a value from a hidden inputbox using JavaScript. However, I am encountering issues where sometimes I receive an "undefined" error and other times there is no output at all. When I utilize alert(document.getElementById('hhh& ...

What is the best approach to implement a basic image upload functionality?

I have a vision for my new website where users can upload an image with the click of a button, store it locally on one page and then retrieve its absolute URL to share on forums or other websites for preview purposes. While I've managed to create a fu ...

JavaScript - Modifying Text within a Dropdown Menu

I'm currently working with a code that generates a dropdown menu/selector. Upon selecting an option, the main display should change accordingly. While I can't directly modify the code, I have the ability to use JQuery to alter the displayed text. ...

Extracting values from a JSON object in JavaScript

Is there a way to retrieve the _id and state values from the provided data? Check out the data { "data": { "totalSamplesTested": "578841", "totalConfirmedCases": 61307, "totalActiveC ...

Triggering animation with jQuery and CSS

I am working on a one-page site and I want to make a parallelogram disappear when a button is clicked for the next part. Currently, it is disappearing from right to left but I would like to change the direction to left to right. Additionally, I have a simi ...

invoking a function by utilizing nested controllers

Struggling with nested controllers, the main goal of this code is to link data extracted from a .json file to another function or file. .html file: <div ng-app="myApp" ng-controller="GetCtrl" > <li ng-controller="ChannelCtrl" ng-repeat="x in ...

Combining Components in NextJs Without Using Functional Components

I created a module, then split it into components and now I'm trying to piece it back together. The individual components are functioning correctly. Some components are nested inside the div of another component. I attempted to group them within a d ...

Is there a way to trigger a Javascript alert and then navigate to a different page in Django once the user presses 'ok'?

On my Django website, I have a contact form that triggers when the submit button is clicked. I want to display a Javascript alert notifying the user that their message has been sent and then redirect them back to the homepage. While I have successfully i ...

Troubleshooting: Bootstrap CSS Bottom Class Issue

I'd like the text to sit right on top of the background image, with the message fixed in place at the bottom of the container. I've tried setting 'bottom: 0;' but it doesn't seem to work. The layout needs to be responsive, so I can ...