Tips for Deselecting a Table Cell in React

I've been working on a table in React and I'm trying to implement a feature where clicking on a cell colors it, and clicking on another cell uncolors the previous one. So far, I've managed to color cells upon clicking but I'm stuck on how to uncolor them when a different cell is clicked. Since the cell itself doesn't know about other cells being clicked, I'm having trouble figuring out the best approach. As a result, multiple clicks leave me with numerous colored cells instead of just one.

Below is my current cell code:

class Cell extends React.Component {

    state = {
        bgColor: 'inherit'
      }

    handleClick = (columnId) => {
        this.setState({
            bgColor: "blue"
        })
    }

    render() {

        const content = this.props.content;

        return (
            <td
                onClick={()=> this.handleClick()}
                style={{backgroundColor: this.state.bgColor}}
            >
                {content}
            </td>
        )
    }
}

Thank you for any assistance you can provide!

Answer №1

I have figured out how to change the color of cells when they are clicked, but I am stuck on how to revert the color back when another cell is selected. The issue lies in the fact that each cell object does not know when a different cell has been clicked.

To address this, it is important to establish a single source of truth so that all components are aware of the active cell. In the code snippet below, I have placed the activeCell state in the parent component App, which allows for the accurate tracking of the active cell. By passing down the necessary props to the Cell component, you can update the new activeCell value upon clicking.

class Cell extends React.Component {
  render() {

    const content = this.props.content;

    return (
      <td
          onClick={()=>{this.props.handleChangeActiveCell(this.props.identifier)}}
          style={{backgroundColor: this.props.activeCell === true ? this.props.bgColor : 'inherit'}}
      >
          {content}
      </td>
    )
  }
}

class App extends React.Component {

  state = {
    bgColor: "blue",
    activeCell: -1
  }
  
  handleChangeActiveCell = (key) => {
    this.setState({
      activeCell: key
    });
  }

  render(){
    return(
      <React.Fragment>
        <table>
          <tr>
            <Cell 
              identifier={0} 
              handleChangeActiveCell={this.handleChangeActiveCell} 
              activeCell={this.state.activeCell === 0 ? true : false} 
              bgColor={this.state.bgColor} 
              content={`sample_content`}
            />
            
            <Cell 
              identifier={1} 
              handleChangeActiveCell={this.handleChangeActiveCell} 
              activeCell={this.state.activeCell === 1 ? true : false} 
              bgColor={this.state.bgColor} 
              content={`sample_content`}
            />
          </tr>
        </table>
      </React.Fragment>
    );
  }
}

ReactDOM.render(<App/>, document.getElementById("root"));
td {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></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

Switch out a specific string within a JavaScript object

{ 1:' {person} experimenting for 1 ', 2:'{person} experimenting for 2 ', 3:'{person} experimenting for 3 ', 4:'{person} experimenting for 4 ', 5:'{person} experimenting for 5 ' } Imag ...

Utilize parameter passing in React URL to fetch specific data based on context

I have successfully created an express API that allows me to retrieve data based on different music genres. For example, by passing parameters to the URL such as localhost:8000/data?music=rock or localhost:8000/data?music=rap, I am able to fetch data assoc ...

Sorry, I am unable to fulfill this request as it involves rewriting copyrighted content. However, I can provide some

Whenever I attempt to execute create-react-app myapp, I keep encountering an error. I have also attempted to clear the cache using npm cache clean --force Unfortunately, this did not resolve the issue. internal/modules/cjs/loader.js:638 throw err; ^ Er ...

React dependency installation problem encountered

npm install axios moment react-file-base 64 redux redux-thunk npm ERR! 404 npm ERR! 404 Note that you can also install from a npm ERR! 404 tarball, folder, http url, or git url. npm ERR! A complete log of this run can be found in: C:\Users\apa10 ...

Flashing shadow effect occurs on Material-UI Dialog background in specific scenarios

How can I add tabs to a material-ui dialog without the background shadow flickering in dark themes when the tab switches? Check out the demo here: https://codesandbox.io/s/stoic-tu-5p9wl ...

Is it possible to integrate React Bootstrap with Next.js?

Is it possible to integrate react-bootstrap with Next.js? I have the latest versions of both, but none of my react-bootstrap components are showing up in my app. I've searched online for solutions, but haven't found anything helpful. If needed, I ...

Ways to eliminate hover effect in CSS

I have a text that is currently displayed as a hyperlink, and some CSS code is causing it to underline and become bold when hovered over. I want to remove the hyperlink, but still keep this style by default without needing to hover over the text. Here is m ...

Tips for designing a sleek and seamless floating button

I attempted to implement a floating button feature that remains in view while smoothly flowing using jQuery. I followed a tutorial I found online to create this for my website. The tutorial can be accessed at this link. However, after following all the ste ...

Modal Pop-ups Failing to Open on Subsequent Attempts

My table consists of buttons on the right-hand side for a menu. The first button in the menu is supposed to open a modal box upon clicking. However, the first buttons in the subsequent rows do not function as expected and fail to open the modal. Refer to t ...

The Vertical Alignment Issue with Material UI's <TextField/> Label

I am trying to align the Typography and TextField of Material UI vertically. Below is my code snippet: <Grid container> <Grid item xs={12} sm={3}> <Typography>1.1 Company Name</Typography> </Grid> <Grid ...

How to customize TextField error color in Material-UI using conditional logic in React

Currently, I am incorporating the React Material-UI library into my project and faced with a challenge of conditionally changing the error color of a TextField. My goal is to alter the color of the helper text, border, text, and required marker to yellow ...

I would like to share tips on integrating React.js with a backend through React Hooks and the process of deploying the application on Heroku

Looking to integrate the React front-end framework with my backend express.js and EJS using React Hooks. I am familiar with using app.get() in Express for handling server requests, but unsure how to coordinate that with starting a React server on localh ...

Creating a tabular layout using div elements and CSS styling

Here is the css and html code that I am working with: <style type="text/css"> .formLayout { background-color: #f3f3f3; border: solid 1px #a1a1a1; padding: 10px; width: 300px; border-radius: 1em; } ...

Guide on creating a scrollable material ui chips array with left and right navigation arrows

I need help with creating a horizontal scrolling effect for material ui Chips within a single line. Take a look at the code sandbox I have been working on: CodeSandbox ...

Is there a way to position two forms next to each other in alignment?

I would like to display two forms side by side. Currently, I have one form shown here: http://gyazo.com/093efe95337ace40fe633adb88b76c2d. I want the same form to be displayed on the right-hand side as well. .comments-section .comment-form { padding: 20p ...

What are the distinct components used in CSS for :target?

I've encountered an issue with nesting :target pseudoclasses. Currently, I have a section containing an anchor tag. Right now, everything is functioning as intended; when I click on the anchor linking to #Current, it expands the area and displays the ...

Positioning tooltip arrows in Highcharts

I'm attempting to modify the Highcharts tooltip for a stacked column chart in order to have the arrow on the tooltip point to the center of the bar. I understand that I can utilize the positioner callback to adjust the tooltip's position, but it ...

Generate a temporary file, retrieve the file using axios within a React component, and prompt a download message to the

Within my application, there is a requirement to generate a binary file with a custom extension and then send it to the client. The client sends a request using axios, and on the server side, I need to dynamically create the file (in a temporary location, ...

Using single page anchor tags in Next.js to toggle content visibility

The Issue Currently working on a project using Next.js and facing a challenge: needing to hide or replace content based on the selected category without reloading the page or navigating to another route. Furthermore, ensuring that when the page is reloade ...

Having trouble with React? The link to the component refuses to load until the page is manually

React Component Link Not Loading Without Page Refresh I'm facing an issue where the link to the terms and conditions won't load unless I refresh the page. You can watch the video below for more context. https://youtu.be/2QumWBRXiuM Below is the ...