A guide on customizing column names in MUI Datatables through object keys

I'm currently facing an issue where I need to set the name of a column in MUI Datatables using an object key. Specifically, I want to set one of the column names with the first element of children.childName so that it displays a list of child names, but only the first child.

Unfortunately, my current approach does not seem to be working as expected. There are no errors, yet nothing is being displayed in the childName Column on the table.

I'm curious if there's a way for me to access an object inside an array?

https://i.stack.imgur.com/jHMVQ.png

Here's an example of my Data:

    const data = [
  {
    name: "Pat",
    company: "Test Corp",
    city: "Yonkers",
    state: "NY",
    children: [
      { childName: "Pat Jun", childAge: 2 },
      { childName: "Mary Jun", childAge: 2 }
    ]
  },
];


    const columns = [
  {
    name:name: data[0]["children"][0]["childName"],
    label: "Child Name",
    options: {
      filter: true,
      sort: true
    }
  }]

MuiTable.js

function MuiTable({ forms }) {
  console.log("cols", columns);
  return (
    <MUIDataTable
      title={"Title"}
      data={data}
      columns={columns}
      options={options}
    />
  );
}

When I use a console.log, I can see that it is printing the value instead of the object key name

https://i.stack.imgur.com/TUvdY.png

I would greatly appreciate any assistance. Thank you.

Answer №1

Here is an example of how you can use the customBodyRender in your React application:

import React from "react";
import ReactDOM from "react-dom";
import MUIDataTable from "mui-datatables";
import { Typography } from "@material-ui/core";

import "./styles.css";

function MyApp() {
  const data = [
    {
      name: "John",
      company: "ABC Inc.",
      city: "New York",
      state: "NY",
      children: [
        { childName: "Max", childAge: 5 },
        { childName: "Sophia", childAge: 4 }
      ]
    }
  ];

  const columns = [
    {
      name: "children",
      label: "Child Names",
      options: {
        filter: true,
        sort: true,
        customBodyRender: (value, tableMeta, updateValue) => (
          <Typography>
            {value.map(child => child.childName).join(",")}
          </Typography>
        )
      }
    }
  ];

  return (
    <div>
      <MUIDataTable title={"My Table"} data={data} columns={columns} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyApp />, rootElement);

Answer №2

I extend my gratitude to @Klaus for the valuable input provided in his response. It truly addressed my requirements, although I encountered a slight variation. In my situation, I specifically aimed to purely showcase the initial childName within the children object, which was part of an array consisting of multiple objects. Consequently, some modifications were necessary, including alterations to the data structure.

To overcome this issue, I chose to implement a simple standalone array called childNames into my existing data structure. This separate array exclusively contained the names of the children.

https://i.stack.imgur.com/jWslv.png

Through this adjustment, accessing the childNames became significantly simpler since it was no longer nested. Therefore, I proceeded to display only the first element from this array on the table.

const columns = [
{
  name: "childNames",
  label: "Child Name",
  options: {
    filter: true,
    customBodyRender: (value, tableMeta, updateValue) => {
      return <div>{value[0]}</div>;
    }
  }
},

The primary motive behind creating a dedicated array solely for childNames stemmed from the challenges and complexities faced while attempting to access solely the first childName within the array containing children objects.

Once again, thank you so much for all the assistance provided.

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

My project in WebStorm encounters a setback due to the updated release of Typescript 5+

Recently, I had to upgrade my TypeScript version from 4.9.5 to 5.1.3 because one of the libraries I'm using made a fix that required a newer TypeScript version. After the update, TypeScript started throwing errors for console calls and React event di ...

Exploring the power of Next.js dynamic routes connected to a Firestore collection

Currently seeking a solution to create a dynamic route that will display each document in a Firestore collection using Server-side Rendering. For instance, if there is a document named foo, it would be accessible at test.com/foo under the [doc] page compo ...

Check out the ViewUI Vue.js component that expands to reveal more content!

Is there a simple component to create the expand/collapse button with a blur effect like in all the demos? I see it used across different variations of the demos and am wondering if there is a specific component or demo showcasing how to achieve this effec ...

Angular JS | Sending information to two separate controllers when clicked

I have a series of projects displayed in divs using ng-repeat. Each div contains a link with the project's id. My goal is to bind the project id on ng-click to update a factory. This will enable me to share the clicked project's id with another ...

Empty value for $_POST variable following xmlhttp request

When my code makes an xmlhttp request to a php file with an ID for record deletion from the database, I encounter an issue. The error message 'comicID' is undefined shows up when attempting to delete. This signifies that the variable containing t ...

Use the inline IF statement to adjust the icon class depending on the Flask variable

Is it feasible to achieve this using the inline if function? Alternatively, I could use JavaScript. While I've come across some similar posts here, the solutions provided were not exactly what I expected or were implemented in PHP. <i class="f ...

What is the best way to apply styles when a component is hovered over in the DataPicker material-ui component?

If you want to see a live demo, click here My preference is to modify the border color, label text color, and down icon color on hover. Currently, the default style is in place but I'm wondering if I can change it back to blue? https://i.stack.imgu ...

JavaScript generating HTML code causing malfunctions

I have been attempting to implement the IN Place Editing feature using JQuery. Below is the code snippet editinplace.js $(document).ready(function() { //When div.edit me is clicked, run this function $("div.editme").click(function() { // ...

Jquery is failing to handle multiple inputs

I am currently working on a system that can handle multiple Yes/No questions. However, every time I try to submit the form, I encounter an error in the console that I cannot identify, and no data is returned from the query. Previously, I used an Array to s ...

Crop box overlaying video background

Utilizing jCrop to establish a crop region for a video element. My goal is to make the video section within the crop area fill a container with identical proportions, but I'm encountering challenges with the mathematical calculations. The sizes of th ...

``The presence of symlink leading to the existence of two different versions of React

Currently, I am working on a project that involves various sub custom npm modules loaded in. We usually work within these submodules, then publish them to a private npm repository and finally pull them into the main platform of the project for use. In orde ...

Cut off the initial characters in the URL's hash component

Hey there, I'm currently working on a task that involves removing a specific part of a URL string. Here's the scenario: if (window.location.hash == '#super-super-product') { change.window.location.hash.to.this: #product // this i ...

Optimizing Style Inclusion Order with Vue SFC, vue-loader, and webpack

My Vue/SFC/webpack/vue-loader application integrates bootstrap using 'import', with component styles directly included in the SFCs. However, vue-loader always places bootstrap after the component styles, preventing proper overwrite/cascade over b ...

What is the process for turning off deep imports in Tslint or tsconfig?

Is there a way to prevent deep imports in tsconfig? I am looking to limit imports beyond the library path: import { * } from '@geo/map-lib'; Despite my attempts, imports like @geo/map-lib/src/... are still allowed. { "extends": &q ...

Encountered an issue: Unable to interpret property 'selectionEnd' of null while using autoComplete in Material UI

I am facing an issue with the autoComplete feature in my React project. The react-text-mask component looks like this: <MaskedInput {...other} ref={ref => { inputRef(ref ? ref.inputElement : null); return ref; }} mask={[ /\d ...

Is it possible to reorder two sub-components with React Hooks?

Here's a question that delves into the intricacies of React Hooks: There has been some discussion about the behavior of the setState() returned from the React Hook useState(). It's been mentioned that when we call it, the hook "sets an internal ...

The application experiences crashes when the tablet is rotated, happening while in the development stage

For my web-based Android application project, I am utilizing PhoneGap and Eclipse IDE on a Windows platform. My focus is specifically on Tablet development, more precisely on the Samsung Galaxy Tab 10.1. To develop, I use Eclipse and test the app on the ...

Having trouble with my JQuery image slider... Can anyone help troubleshoot what I might have missed?

I am trying to create a simple image slider, but it doesn't seem to be working. I followed a tutorial on YouTube closely, but since I can't compare my code with theirs on a website, I'm having trouble identifying the mistake. Despite followi ...

What is the best way to apply a hover rule to a CSS class in order to change the color of a specific row when hovering in

I have managed to successfully apply a classname and add color to a specific row in my react-table. However, I am facing difficulty in adding a hover rule to this className to change the color when I hover over the row. Can someone guide me on how to apply ...

What is the most efficient method for transferring rows from an SQL Database to JavaScript?

Recently, I've been exploring the dynamic features of HTML5 IndexedDB controlled by Javascript and how to sync it with an SQL Server database for offline access. The challenge I'm facing is determining the most efficient method to transfer data ...