ReactJS: Creating a “dynamic” render of Row and Col

Asked
Active3 hr before
Viewed126 times

9 Answers

creatingrenderdynamicreactjs
90%

I have made this dynamic data table with dynamic rows and columns editable ,Connect and share knowledge within a single location that is structured and easy to search., Is it safe to unplug an extra monitor from a laptop without turning off the monitor?

<tr Population={zone.population} Zone={zone.name} /> does not seem like a valid React component to me. The lowercase <tr> indicates that this is not a custom component, but represents a standard HTML table row. <tr> elements require <td> or <th> elements inside them, for example:

var rows = [];
this.state.zones.forEach(function(zone) {
    rows.push(
      <tr />
        <td><SomePopulationComponent /></td>
        <td><SomeZoneComponent /></td>
      </tr>
    );
}.bind(this));

You could extract this into a custom element:

var CustomRow = React.createClass({
    render: function() {
        return (
            <tr>
                <td>{this.props.Population}</td>
                <td>{this.props.Zone}</td>
            </tr>
        );
    }
});

// ...

var rows = [];
this.state.zones.forEach(function(zone) {
    rows.push(<CustomRow Population={zone.population} Zone={zone.name} />);
}.bind(this));
load more v
88%

And the function itself

filterDeepUndefinedValues = (arr) => {
   return arr
      .map((val) => val.map((deepVal) => deepVal).filter((deeperVal) => deeperVal))
      .map((val) => {
         if (val.length < 1) {
            val = ["-"];
            return val;
         }
         return val;
      });
};

The return of addTableRow

return row.map((item, index) => {
  return (
    <td
      key={`${item}--${index}`}
      className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"
    >
      {item}
    </td>
  );
});
load more v
72%

In this article I will try to teach how to create a dynamic table in react. Ya I know its quite simple, but this tutorial is for beginners and a beginner should know how to get this kind of stuff done.,You mean let's say you want to generate 3×4 table? I am not really sure but you can store rows and columns numbers into variable and based on that generate the table. ,how to add search and sorting in the table

import React, { Component } from 'react'

class Table extends Component {
   constructor(props) {
      super(props) //since we are extending class Table so we have to use super in order to override Component class constructor
      this.state = { //state is by default an object
         students: [
            { id: 1, name: 'Wasif', age: 21, email: 'wasif@email.com' },
            { id: 2, name: 'Ali', age: 19, email: 'ali@email.com' },
            { id: 3, name: 'Saad', age: 16, email: 'saad@email.com' },
            { id: 4, name: 'Asad', age: 25, email: 'asad@email.com' }
         ]
      }
   }

   render() { //Whenever our class runs, render method will be called automatically, it may have already defined in the constructor behind the scene.
      return (
         <div>
            <h1>React Dynamic Table</h1>
         </div>
      )
   }
}

export default Table //exporting a component make it reusable and this is the beauty of react
load more v
65%

Call the function on component mount to get the inventory data to populate the table. To dynamically create the rows, iterate through the data and use the .map() function.,In this guide, you will learn to build a simple inventory table with the Unit Price column editable to enable updating the price of a product. The table will source its data from a Mock API, which you can create using this guide: Creating a Mock API in React.,Tables are critical for displaying data in web apps. They are often complemented by forms on a different page or on a modal. However, at times, creating a form is hectic when you just need to edit just a column. Hence the need to create editable tables to reduce the hassle of having to build a form for the table. An advantage of this approach is that you also get to improve your app's user experience (UX) by minimizing the interfaces a user has to interact with. You will also be able to load data dynamically populating table rows, ensuring your tables can always have updated data.

1 {
   2 "inventory": [
      3 {
         4 "id": 1,
            5 "product_name": "Weetabix",
            6 "product_category": "Cereal",
            7 "unit_price": "501",
            8
      },
      9 {
         10 "id": 2,
            11 "product_name": "Colgate Toothpaste",
            12 "product_category": "Toiletries",
            13 "unit_price": "119",
            14
      },
      15 {
         16 "id": 3,
            17 "product_name": "Imperial Leather Soap",
            18 "product_category": "Toiletries",
            19 "unit_price": "235",
            20
      },
      21 {
         22 "id": 4,
            23 "product_name": "Sunlight Detergent",
            24 "product_category": "Toiletries",
            25 "unit_price": "401",
            26
      }
      27
   ]
   28
}
load more v
75%

renderRow component: This component would contain the logic where the columns of a particular row will be returned.,If we setup a code with the above requirements, our code would be as follows:,getHeader function: This function would contain the logic that would return the header (component) part of the table

By the end of the article we will be creating a component that will be used as follows:

<Table data={this.state.data}/>
load more v
40%

Basically, I need to show this data in a tabular form. So let’s create a table header first. A const variable is created with a name columnHeader. To make the table header dynamic the data should be from the backend or should be a dynamic way to fetch.,In order to use the employe data from employ.json file, we need to import that file. Below image shows the importing of employ file and columnHeader name.,In the previous tutorial, we had covered a simple example of a table now will try to understand a better design approach for table creation. Instead of code repetition, let’s make it more dynamic to reduce the code.

import React from 'react';
import employ from './employ.json';
const columnHeader =["Id","firstName","lastName","email","gender"];
export default class ChildComponent extends React.Component{
   constructor(props){
       super(props);
       this.state={
       }
       this.generateHeader = this.generateHeader.bind(this);
       this.generateTableData = this.generateTableData.bind(this);
   }
   generateHeader(){
       let res=[];
     for(var i =0; i < columnHeader.length; i++){
         res.push(<th key={columnHeader[i]}>{columnHeader[i]}</th>)
     }
     return res;
   }
   generateTableData(){
       let res=[];
       let tableData = employ.data;
       for(var i =0; i < tableData.length; i++){
           res.push(
            <tr >
           <td key={tableData[i].id}>{tableData[i].id}</td>
           <td key={tableData[i].firstName}>{tableData[i].firstName}</td>
           <td key= {tableData[i].lastName}>{tableData[i].lastName}</td>
           <td key={tableData[i].email}>{tableData[i].email}</td>
           <td key={tableData[i].gender}>{tableData[i].gender}</td>
           </tr>
           )
       }
       return res;
   }
   render(){
       return(
           <div>
        <table className="table  table-hover">
        <thead>
            <tr>
            {this.generateHeader()}
            </tr>
        </thead>
        <tbody>
            {this.generateTableData()}
        </tbody>
        </table>
           </div>
       )
   }
}
load more v
22%

Bootstrap has a class called row which we use as the container class. Any items inside that element will appear as columns in that row.,I’m using Bootstrap for helping to style the website, and the issue is there doesnt appear to be a nice way for me to dynamically render rows with items in them (you have to decide the rows and columns up font to define the grid).,What we’re returning is a list of div elements with a class of row. In each of those elements, we just render an h1 tag for each item in the rows object.

class Items extends React.Component {
  constructor() {
    super()
    this.state = {
      items: [1, 2, 3, 4, 5, 6, 7, 8, 9],
    }
    this._createItemList.bind(this)
  }
  _createItemList() {
    let rows = {}
    let counter = 1
    this.state.items.forEach((item, idx) => {
      rows[counter] = rows[counter] ? [...rows[counter]] : []
      if (idx % 4 === 0 && idx !== 0) {
        counter++
        rows[counter] = rows[counter] ? [...rows[counter]] : []
        rows[counter].push(item)
      } else {
        rows[counter].push(item)
      }
    })
    return rows
  }
  render() {
    let rows = this._createItemList()
    console.log(rows)
    return (
      <section className="section items">
        <div className="container">
          {Object.keys(rows).map(row => {
            return (
              <div className="row items__row" key={row}>
                {rows[row].map(item => {
                  return <h1>{item}</h1>
                })}
              </div>
            )
          })}
        </div>
      </section>
    )
  }
}

ReactDOM.render(<Items />, document.getElementById("app"))
load more v
60%

the column array allows us to decide which column names we want to display in the data rows, ,using map() function we are able to reduce the amount of code – columns and data arrays are mapped into React components.,Remember that each element should have a unique key - it helps React optimally manage changes in the DOM. Such a key may be for example the path assigned to each element of the table.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const tableStyle = {
  border: "1px solid black",
  borderCollapse: "collapse",
};

const tdStyle = {
  border: "1px solid black",
};

const Table = ({ id, columns, data }) => (
  <table style={tableStyle}>
    <tbody>
      <tr>
        {columns.map(({ path, name }) => (
          <th style={tdStyle} key={path}>{name}</th>
        ))}
      </tr>
      {data.map((rowData) => (
        <tr key={rowData[id]}>
          {columns.map(({ path }) => (
            <td style={tdStyle} key={path}>
              {rowData[path]}
            </td>
          ))}
        </tr>
      ))}
    </tbody>
  </table>
);

// Example use --------------------

const App = () => {
  const columns = [
    { path: "id",   name: "ID" },
    { path: "name", name: "Name" },
    { path: "age",  name: "Age" },
  ];

  const data = [
    { id: 1, name: 'Kate',  age: 25, favFruit: '🍏' },
    { id: 2, name: 'Tom',   age: 23, favFruit: '🍌' },
    { id: 3, name: 'Ann',   age: 26, favFruit: '🍊' },
    { id: 4, name: 'Jack',  age: 21, favFruit: '🍒' }
  ];

  return (
    <div>
      <Table id="id" columns={columns} data={data} />
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
48%

The render() method renders a table with three columns: "ID", "Name", and "Value".,To start, create a React app with the create-react-app command. You can learn how to set create-react-app up in React Crash Course for Beginners.,Check out how you would style different columns with different colors.

To start, create a React app with the create-react-app command. You can learn how to set create-react-app up in React Crash Course for Beginners.

create - react - app react - table - app
load more v

Other "creating-render" queries related to "ReactJS: Creating a “dynamic” render of Row and Col"