Home > front end >  AGGrid React Custom Header Component - Updating state
AGGrid React Custom Header Component - Updating state

Time:10-07

I've taken over a React project and I'm fairly new to the library. I'm attempting to implement AG-Grid and what I think is a relatively simple custom header that renders the column name and an icon. When the icon is clicked, I need the icon to change and update the state of the custom header components parent.

My issue is that the click event works once and updates the state in the parent, but the state doesn't propagate back down to the custom header component and therefore the icon doesn't switch. Not sure if this is an AG Grid issue or a React issue.

My Custom Header Component

const WeightHeaderComponent = (params) => {
  const handleClick = () => {
    params.weightModeCallback()
  }
  return (
    <span onClick={handleClick} style={{cursor: 'pointer'}}>
      Weight<i className={`${params.weightModeIsPercent ? 'fa fa-percent cn-blue' : 'fa fa-tally cn-blue'}`} style={{marginLeft: '3px'}}></i>
    </span>
  );
};

The AG Grid column def using the custom header component:

const [columnDefs] = useState([
...
  {
      headerName: 'Weight',
      field: 'weight',
      type: 'numericColumn',
      headerTooltip:
        'The weight of an assignment category determines the impact an assignment will have over your overall grade.',
      width: 100,
      defaultMinWidth: 100,
      headerComponentParams: { weightModeIsPercent: weightModeIsPercent, weightModeCallback: updateWeightMode },
      headerComponent: WeightHeaderComponent
    },
...
])

The relevant state hook:

const [weightModeIsPercent, setWeightModeIsPercent] = useState(true);

And finally my callback function in the parent

  function updateWeightMode () {
    setWeightModeIsPercent(!weightModeIsPercent);
  }

CodePudding user response:

Try using

api.refreshHeader();

CodePudding user response:

After an hour of so of doc reading and head-desk beating I figured it out. I was attempting to do this in a very roundabout way when AG Grid offers a nice little api which happens to have some functions for exactly this type of thing: updating your columnDefs.

Specifically: setColumnDefs(newDefs).

My code accepts an updated parameter with which I update the columnDefs for the column I want to update.

  function updateWeightMode (updatedWeightModeBool) {
    const newDefs = columnDefs.map((def) => {
      if (def.field === 'weight') {
        return {
          ...def,
          headerComponentParams: {
            weightModeIsPercent: updatedWeightModeBool,
            weightModeCallback: updateWeightMode
          }
        };
      }

      return def;
    });
    weightsGridRef.current.api.setColumnDefs(newDefs);
  }

So, this wasn't really an issue with state (though I'm still updating the parents state for other uses).

  • Related