Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic column and values in react table

Tags:

reactjs

response : {initial_data: [{
 "Did I see this plant in 2016?"=>"No",
 "Did I see this plant in 2017?"=>"Yes",
 "How Many?"=>1,
 "User Data 4"=>"x",
 "User Data 5"=>nil,
 "Did I see this plant in 2022?"=>"No",
 "Name"=>"Abronia alpina"},
 {"Did I see this plant in 2016?"=>"No",
 "Did I see this plant in 2017?"=>"No",
 "How Many?"=>11,
 "User Data 4"=>"x",
 "User Data 5"=>nil,
 "Did I see this plant in 2022?"=>"Yes",
 "Name"=>"Abronia alpina1"}]
}

Based on above response I am executing below code to print the header and there values dynamically.

const CUSTOM_COLUMNS = (Object.keys(props.initial_data[0].map((item, index) =>
                            [{
                              id: 'user_data',
                              Header: item,
                              headerClassName: 'family-header',
                              accessor: item,
                              className: 'centered capitalize',
                              show: true
                            }][0]
                          ));

const columns = [
  ...CUSTOM_COLUMNS,
  {
    Header: 'Actions',
    accessor: 'id',
    show: true,
    className: 'centered',
    Cell: (props) => (
      <span className="label label-danger link" onClick={this.deletePlant.bind(this, props.value)}>
        <i className="fa fa-trash"></i> Delete
      </span>
    )
  }
];

I able to correctly print the header dynamically, but my values are not coming dynamically and it's displaying my last hash key values in each column.

My header should be :

["Did I see this plant in 2016?", "Did I see this plant in 2017?", "How Many?", "User Data 4", "User Data 5", "Did I see this plant in 2022?", "Name"]

and row values should be:

Row1 : ["No", "Yes", 1, "x", "", "No", "Abronia alpina"]
Row1 : ["No", "No", 11, "x", "", "Yes", "Abronia alpina1"]

Can you please help me to get it dynamically, or let me know what I am doing wrong here. I am new in react so maybe i am missing here so please correct me.

like image 252
Vik Avatar asked Feb 12 '18 14:02

Vik


People also ask

How to get column values from header in react-table?

With React-Table you header must have a accessor and your data must be mapped with accessor as the key getColumns () { return Object. keys (data. initial_data [ 0 ]). map ( key => { return { Header: key, accessor: key }; }); } Accessors are functions that return the value to populate the row's value for the column.

What does react do when the Dom is updated?

The React-Gods can skip this paragraph. When the DOM is being updated, what React does is it first renders the component.

How do I populate data from a mock API in react?

To populate data, make a GET request to the Mock API URL you created. Define the API_HOST of your Mock API and the endpoint. This is done outside the App function: Use React Hooks to define state and lifecycles in the app. Start by defining a state variable to store the data from the Mock API. The default value is set to an empty array.


2 Answers

With React-Table you header must have a accessor and your data must be mapped with accessor as the key

You would create your columns like

  getColumns() {
    return Object.keys(data.initial_data[0]).map(key => {
      return {
        Header: key,
        accessor: key
      };
    });
  }

and you Table can then look like

class App extends React.Component {
  getColumns() {
    return Object.keys(data.initial_data[0]).map(key => {
      return {
        Header: key,
        accessor: key
      };
    });
  }
  render() {
    const columns = this.getColumns();
    console.log(data.initial_data);
    return (
      <div>
        <ReactTable
          data={data.initial_data}
          columns={columns}
          defaultPageSize={10}
          className="-striped -highlight"
        />
        <br />
        <Tips />
        <Logo />
      </div>
    );
  }
}

According to documentation:

accessor: 'propertyName', // or Accessor eg. (row) => row.propertyName

Accessors are functions that return the value to populate the row's value for the column. This lets the render function not have to worry about accessing the correct data, the value is automatically populated in it's props.

If a string or array is passed the default accessor is used. The default accessor will parse the input into an array and recursively flatten it. Any values that contain a dot (.) will be split. Any values that contain bracket ([]) will be split. This array is then used as the path to the value to return.

Working Codesandbox

like image 23
Shubham Khatri Avatar answered Sep 21 '22 08:09

Shubham Khatri


If you are using react-table, to render the table, I think your logic of creating columns is wrong. It should be something like this.

const columns = Object.keys(response.initial_data[0]).map((key, id)=>{
  return {
    Header: key,
    accessor: key
  }
})

I have tried to create a snippet with your data. Let me know if this helps.

const ReactTable = window.ReactTable.default

const response = {
  initial_data: [
   {
     "Did I see this plant in 2016?":"No",
     "Did I see this plant in 2017?":"Yes",
     "How Many?":1,
     "User Data 4":"x",
     "User Data 5":"",
     "Did I see this plant in 2022?":"No",
     "Name":"Abronia alpina"
   },
   {
     "Did I see this plant in 2016?":"No",
     "Did I see this plant in 2017?":"No",
     "How Many?":11,
     "User Data 4":"x",
     "User Data 5":"",
     "Did I see this plant in 2022?":"Yes",
     "Name":"Abronia alpina1"
   }]
}

class App extends React.Component {

  render() {
    const data = response.initial_data

    const columns = Object.keys(response.initial_data[0]).map((key, id)=>{
      return {
        Header: key,
        accessor: key
      }
    })

    return <ReactTable
      data = { data }
      columns = { columns }
    />
  }
}

ReactDOM.render( < App / > , document.getElementById("app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-table/6.7.6/react-table.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/react-table/6.7.6/react-table.css"></link>
<div id="app"></div>
like image 103
Dev Avatar answered Sep 22 '22 08:09

Dev