Is is possible to set color of the text in a cell programmatically? Well my scenario is i have some numbers filling in the data-grid. I want to color them according to their values. I'm kind of lost here because i didn't found a way to customize a single cell. I've tried the 'rowRender' but it doesn't accomplish my task since it only colors a row. What i want is to color a single cell. Is it possible to do this.
Asked
Active
Viewed 1,727 times
1 Answers
3
Yes we can format the column according to the data. Please see the following example to understand how to achieve it,
import ReactDOM from "react-dom";
import React from "react";
import ReactDataGrid from "react-data-grid";
import "./styles.css";
class NameFormatter extends React.Component {
render() {
return (
<span className={this.props.dependentValues.id === 1 ? "red" : "green"}>
{this.props.value}
</span>
);
}
}
let columns = [
{
key: "id",
name: "Id",
getRowMetaData: row => row
},
{
key: "name",
name: "Name",
getRowMetaData: row => row,
formatter: NameFormatter
}
];
class App extends React.Component {
constructor() {
super();
this.state = {
data: [{ id: 1, name: "einsten" }, { id: 2, name: "newton" }]
};
this.rowGetter = this.rowGetter.bind(this);
this.getSize = this.getSize.bind(this);
}
rowGetter(rowIndex) {
let rows = this.getRows();
return rows[rowIndex];
}
getRows() {
return this.state.data;
}
getSize() {
return this.getRows().length;
}
render() {
return (
<ReactDataGrid
columns={columns}
rowsCount={this.getSize()}
rowGetter={this.rowGetter}
/>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Inorder to customize the column we need to write a formatter component,here Nameformatter
is the formatter component for the name
column .We can access the column value via this.props.value
and the meta data(Other column values) through this.props.dependentValues.nameoffield
in the formatter component.
See the working example

Harikrishnan
- 1,097
- 8
- 13
-
@NimeshaKalinga Sorry i didn't understand your requirements.Please elaborate – Harikrishnan Sep 25 '18 at 11:45
-
Oh, nevermind, that was my bad, i could access the data from the props, i accept your answer, thanks – Nimesha Kalinga Sep 25 '18 at 11:51
-
This is the best answer out there! – JAN Nov 27 '19 at 05:16