Nimesha Kalinga
Nimesha Kalinga

Reputation: 261

How to set color of the text in a cell programatically

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.

Upvotes: 3

Views: 1831

Answers (1)

Harikrishnan
Harikrishnan

Reputation: 1097

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

Upvotes: 3

Related Questions