1

I am using ag grid in one my react applications. I am initializing my grid in one of the components and saving the gridApi on a state variable by useState inside onGridReady method.

The thing is, I want to access gridApi from some other components also. What's the best practice for it? For example, I am initializing my grid in X component and I want to access gridApi from Y component also. Currently I am storing the gridApi on redux and retrieving it from store whenever it's needed from other components. Is there any other better way to do it? Also is there any pitfall of storing gridApi in redux?

Thank you.

zze159753
  • 55
  • 1
  • 5

1 Answers1

1

Since you're using React, there's a few approaches you can use to access the gridApi from other components. All three approaches work well, depending on your needs.

  1. Prop Drilling

Let's say you have a parent component which has a grid component and another component as children components. You can define a state variable on the parent component, and then provide a callback to the grid component to set the state when the grid is initialised. Now that you have the gridApi in the parent, you can share it with the other child component by passing it as props. You can find the implementation of this in a stackoverflow question I answered which has the solution.

  1. Global state (Redux)

I can see that you're currently using this method.

  1. Context / useContext

Similar to the Redux approach, but instead keeping the gridApi using React Context

Shuheb
  • 2,012
  • 1
  • 4
  • 6