0
  • here I got all data of contact in CCcontact and column name in cc state from backend API and I want to show this all data in the table
  • for this, I used two maps in the first one I getting all contact data and second map for a column that I need to show in table but its didn't work.
function CustomColumn(){
  const [CCcontact, setCCContact] = useState([]);
  const [cc, setCc] = useState([]);

  return (
    <>
      <div className="w-75 hi">
        <table className="table">
          <thead className="thead-dark">
            <tr>
              {cc.map((cc) => {
                  return <th scope="col">{cc.name}</th>;
                })}
            </tr>
          </thead>
          <body>
            /* getting contact data */
            {CCcontact.map((contact) => {
                return (
                  <tr>
                     /* getting column */
                    {cc.map((column) => {
                        let c = column.name 
                        //this isn't working
                        return <td>{contact.c}</td>;
                      })}
                  </tr>
                );
              })}
          </tbody>
        </table>
      </div>
    </>
  );
}
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • 1
    `c` is a dynamic value, the name of the column. So it's not `contact.c`, because that refers to a property literally named "c". For dynamic keys you use square brackets, i.e. `contact[c]` – Jayce444 May 21 '21 at 04:38
  • Change `contact.c` to `contact[c]` – ray May 21 '21 at 04:39

1 Answers1

0

This is working for me.

You should change Contact.c to Contact[c].

import "./styles.css";
import React, {useState} from 'react';

export default function CustomColumn(){
  const [CCcontact, setCCContact] = useState([
    {a: "aa"},
    {b: "bb"},
    {c: "cc"},
    {d: "dd"}
  ]);
  const [cc, setCc] = useState([
    {name: "a"},
    {name: "b"},
    {name: "c"},
    {name: "d"},
  ]);

  return (
    <>
      <div className="w-75 hi">
        <table className="table">
          <thead className="thead-dark">
            <tr>
              {cc.map((cc) => {
                  return <th scope="col">{cc.name}</th>;
                })}
            </tr>
          </thead>
          <tbody>
            {CCcontact.map((contact) => {
                return (
                  <tr>
                    {cc.map((column) => {
                        let c = column.name 
                        //this isn't working
                        return <td>{contact[c]}</td>;
                      })}
                  </tr>
                );
              })}
          </tbody>
        </table>
      </div>
    </>
  );
}
Zhang TianYu
  • 1,163
  • 5
  • 11