Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 625
user3802348 Avatar asked Mar 02 '26 20:03

user3802348


1 Answers

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
};
like image 89
ghost_dad Avatar answered Mar 04 '26 10:03

ghost_dad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!