Unable to retrieve table header information when clicking on a table cell

My code is working perfectly, except for the fact that when I click on a cell, I cannot retrieve the table header text. Retrieving the row text works fine based on the code. If I use Object.keys(data) inside the alert function to retrieve the data, it gives me all the header text instead of the corresponding cell. I am using semantic-ui-react table.

class NonProtectedFeatureBias extends Component {
    constructor(props){
        super(props);
        this.state = {       
            staticPostData:{
                dataset_id: 1
            },
            tableData:{},
        };
    }
    renderKeys (data) {
        return Object.keys(data).map(item => (<Table.HeaderCell>{item}</Table.HeaderCell>))
    }
    renderValues (data) {
        const rows = {}
        Object.values(data).forEach(col => {
          for (let [key, value] of Object.entries(col)) {
            rows[key] = rows[key] ? [...rows[key], value] : [value]
          }
        })

        return Object.entries(rows).map(([item, values]) => (
          <Table.Row>
            <Table.Cell>{item}</Table.Cell>
              { 
                values.map(val => 
                    <Table.Cell 
                        className={ val === 'Low' ? ('green-color') : val === 'High' ? ('red-color') : ('orange-color') } 
                        selectable
                        onClick={()=>{
                            alert(Object.keys(data) + " " + item);
                        }}
                        verticalAlign='middle'
                        > {val}
                    </Table.Cell> ) 
              }
          </Table.Row>
        ))
    }

    componentDidMount() {
        this.fetchData();
    }
    fetchData(){
        axios.post('http://localhost:5000/GetProxyTable', this.state.staticPostData)
         .then((response) =>{
            this.setState({tableData:response.data})

        });
    }
    render(){
        return ( 
            <Container style={{height:"250px", backgroundColor:""}}>
                <Table definition style={{marginTop:"5px"}} key="mytb">
                    <Table.Header>
                        <Table.Row className="cell-with-no-padding">
                            <Table.HeaderCell className="cell-width-single" />
                            {this.renderKeys(this.state.tableData)}
                        </Table.Row>
                    </Table.Header>

                    <Table.Body>
                        {this.renderValues(this.state.tableData)}
                    </Table.Body>
                </Table>
            </Container>
        );
    }
}
export default NonProtectedFeatureBias;

Here is the response I received from the API. https://i.sstatic.net/KwFH3.png

Any suggestions would be greatly appreciated.

Answer №1

Using Object.keys(data) will give you access to all columns. You can then use the index to specifically target a column.</p>

<p><strong>Here's how you can do it:</strong></p>

<pre class="lang-js"><code>Object.keys(data)[index]

Check out this code snippet:

...
<Table.Cell>{item}</Table.Cell>
{ 
    values.map((val,index) => //<-------------- utilize the index
        <Table.Cell 
            className={ val === 'Low' ? ('green-color') : val === 'High' ? ('red-color') : ('orange-color') } 
            selectable
            onClick={()=>{
                alert(Object.keys(data)[index] + " " + item); //<----- utilizing the index here
            }}
            verticalAlign='middle'
            > {val}
        </Table.Cell> ) 
...

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

Describing a function in Typescript that takes an array of functions as input, and outputs an array containing the return types of each function

Can the code snippet below be accurately typed? function determineElementTypes(...array: Array<(() => string) | (() => number) | (() => {prop: string}) | (() => number[])>) { /// .. do something /// .. and then return an array ...

Automatically updating div content using a static HTML page

Is there a way to refresh the content of an HTML div tag every 5 minutes without having to reload the entire page? <div id="pie"> <script src="index.js">// this script should be reloaded every 5 minutes </script& ...

Saving the Structure of an XML Document Using JQuery

Xml: <Data> <Cat> <Name>Fluffy</Name> </Cat> <Cat> <Name>Willy</Name> </Cat> </Data> JQuery: // ...Executing ajax requests... $(xml).find('Cat').each(function ...

Retrieve a compilation of Whole Foods locations through the use of rvest

I want to retrieve a list of Whole Foods stores using the rvest package. I've successfully extracted information from various sources like Wikipedia, FIFA, and Yahoo! Finance using this method. However, in this case, the table spans multiple pages but ...

bootstrap used for creating horizontal radio buttons

I'm attempting to horizontally align radio buttons within a form without relying on the Bootstrap library. The following code achieves this: <form id="test_form"> <div class="control-group"> <label for="Q1">First question</ ...

JavaScript functions cannot be applied to input fields in jQuery

I am having trouble saving values into a database where I need to calculate the total and grand total. I want to do the calculation in the input field, but my attempts have not been successful. It seems like the issue lies with $('.multTotal',thi ...

Integrating external information with components

Currently in my React application, I am fetching a list of stores by directly calling the API through the URL. const getStore = async () => { try { const response = axios.get( 'http://localhost:3001/appointment-setup/storeList& ...

The request has been denied due to CORS policy restrictions. The 'Access-Control-Allow-Origin' header is not included when setting the content-type to multipart/form-data

I'm new to working with react and nodeJS, and I've run into an issue when trying to update and insert data with image upload using multer. I am sending the data as formData. However, I keep getting a CORS error stating "Request blocked by CORS w ...

I am encountering a problem while attempting to fetch information from Firestore through the Firebase JS SDK

My current challenge revolves around retrieving data from Firestore using the Firebase JS SDK. A specific error message persists: An unexpected issue arises: TypeError: firebase_firestore__WEBPACK_IMPORTED_MODULE_3__.getDoc(...).data is not a function I ...

Top choice for recording sound and video over the internet

Seeking assistance in finding solutions to enable recording audio and video via web on different platforms such as iPhone and iPad. The recorded media needs to be saved on the server. Any recommendations for a cross-browser compatible approach are apprecia ...

Guide on sending a message to a specific channel using Discord.js version 13 with TypeScript

After recently diving into TypeScript and seeing that Discord.js has made the move to v13, I have encountered an issue with sending messages to a specific channel using a Channel ID. Below is the code snippet I am currently using: // Define Channel ID cons ...

Can $refs cause issues with interpolation?

I'm currently learning Vue.js and the course instructor mentioned that modifying the DOM element using $refs should not affect interpolation. In fact, any changes made directly to the DOM will be overridden by interpolation if it exists. However, in m ...

Angular and Bootstrap 5 combine to create a dynamic multi-item carousel featuring animated slide transitions and embedded YouTube videos

I'm trying to create a multi-item carousel using YouTube videos, and although I have managed to get it working with Bootstrap 5 carousel and cards, the animation when the carousel slides is not as smooth as I would like. The issue seems to be that the ...

What is the process of invoking a secondary "external" function with Nodejs, Expressjs, and bluebird?

Struggling with creating a nodejs application, a new area for me. I've managed to work with Promises and fetch data from a database. Take a look at the code below: myModel.js var express = require('express'); var app = express(); var Promi ...

Guide on how to modify the color of a single row within a table with just a click

My table structure is as follows: <table> <tr> <td>A1</td> <td>A2</td> <td>A3</td> <td>A4</td> </tr> <tr> ...

Exploring the power of Vue element manipulation

I'm diving into the world of web development and starting my journey with Vue on an online learning platform. Check out the code snippet below: <div id="app"> <form @submit.prevent="onSubmit"> <input v-model="userName"&g ...

Executing multiple asynchronous XMLHttpRequests with React

I experimented with multiple asynchronous XMLHttpRequests based on various examples I came across: var URL=["https://api.github.com/users/github","https://api.github.com/users/github/repos"]; var xhr = [null, null]; for (var i = 0; i < 2; i++) { ( ...

Turn on the text field when the enter key is pressed

I've searched online for solutions, but none of them have resolved my issue. Upon loading my page, I am able to successfully have my JS file select the first textfield. However, I am struggling with getting it to proceed to the next textfield when th ...

Guide on building a custom website loader to display the loading progress of the initial request in Next.js

As I incorporate react three fiber into my website, I've noticed a slight increase in the initial loading time. Instead of just using a useEffect hook with a timeout, I am interested in creating a custom website loader to display the loading progress ...

Java REST service remains out of reach for JavaScript fetch call

Currently, I am in the process of learning about REST API. My goal is to make a call to a POST service implemented in Java from Javascript using fetch. However, I have encountered an issue where the request fails to reach the service whenever the @Produces ...