1

I am using AgGrid for React and I am using class-style react components - not functional components.

My goal is to render the cellStyle based on props conditions.

However, when I want to render it, it renders without even the props are loaded.

How can I fix this?

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
emplo yee
  • 205
  • 2
  • 13

1 Answers1

1

You probably want to call GridApi.refreshCells() to apply the change after updating the column's cellStyle:

const columnDefs = React.useMemo(
  () => [
    {...}
    {
      headerName: "Age",
      field: "age",
      cellStyle: props.styles
        ? { backgroundColor: "pink" }
        : { backgroundColor: "white" }
    }
  ],
  [props.styles]
);

React.useEffect(() => {
  gridApi?.refreshCells({ force: true });
}, [props.styles]);

Live Demo

Class component

Codesandbox Demo

Functional component

Codesandbox Demo

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
  • how would this look like for a class component ? Not sure about that. – emplo yee Oct 16 '21 at 22:10
  • @employee you can check whether your props changed using [`componentDidUpdate`](https://reactjs.org/docs/react-component.html#componentdidupdate) and call `GridApi.refreshCells()` if the new and old prop is different. Do you need an example? – NearHuscarl Oct 16 '21 at 22:15
  • let´s assume i pass a list as a props to a class component. I want to check if a value of a certain row (e.g. 'accountId') is in this list. If yes, colorize it 'green' otherwise 'blue'. How would this work with the refreshcells'refreshCells'? – emplo yee Oct 16 '21 at 22:20
  • @employee do you want to colorize the cell based on the data inside only? or does it depend on the external props? – NearHuscarl Oct 16 '21 at 22:32
  • @employee Not sure if this is what you want but I updated to the class component – NearHuscarl Oct 16 '21 at 22:37
  • it should be based on the props. So if the 'param.data.id' is in the list (provided by the props) then render it green, otherwise blue – emplo yee Oct 16 '21 at 22:53