简体   繁体   中英

How to generate React table with different colored rows?

I'm trying to create a React table in which each row is either gray or white. I am doing this by passing rows the props 'gray' or 'white' upon their creation, but in my MyRow class I'm not sure how to take this prop and convert it to a style.

Relevant code in MyTable.js:

    this.props.items.forEach(function(item) {
        if (i % 2 === 0) {
            rows.push(<MyRow item={item} key={item.name} color={'gray'} />);
        } else {
            rows.push(<MyRow item={item} key={item.name} color={'white'} />);
        }
        i++;
    }.bind(this));

MyRow.js render function:

render() {
    const color = this.props.color;

    const rowColor = {styles.color}; //?? I’m not sure how to do this—how to get color to take on either gray or white?

    return (
        <tr className={styles.rowColor}>
            <td className={styles.td}>{this.props.item.name}</td>
            <td className={styles.editButton}> <Button
                    onClick={this.handleEditButtonClicked}
                />
            </td>
        </tr>
    );
}

MyRow.css:

.td {
    font-weight: 500;
    padding: 0 20px;
}

.gray {
    background-color: #d3d3d3;
}

.white {
    background-color: #fff;
}

I believe you should be able to pass the prop directly to the row as follows, since it's already defined as a string in MyTable.js file:

render() {
    return (
        <tr className={this.props.color}>
            <td className={styles.td}>{this.props.item.name}</td>
            <td className={styles.editButton}> <Button
                    onClick={this.handleEditButtonClicked}
                />
            </td>
        </tr>
    );
}

Also, from the code you have posted, it's unclear where the styles object is located where you're trying to access these properties. If you wanted to access styles.rowColor , you would need a styles object defined:

const styles = {
    rowColor: color
};

Follow this to change individual row cell color using row.value

{
  Header: () => <div className="text-center font-weight-bold">Status</div>,
  accessor: "selectedstatus",
  className: "font",
  width: 140,
  Cell: (row) => (
    <div
      className="text-center h-6"
      style={{ background: row.value === "Selected" ? "green" : "red" }}
    >
      {row.value}
    </div>
  ),
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM