Ajay Bala
Ajay Bala

Reputation: 1

How to Pass data from Grand Child to Parent component. Append the updated state to Child Component in Parent Component

Need to update the state value in Parent component from Grand Child Component. My component tree structure goes like this. Component Tree Structure

I have the state value available in LeftFilter componenet (Grand Child Component). Need to pass to UserList (Parent Component ) and in change handler filter the value and update the state then append the updated state value to DataGrid Component ( Child Component inside UserList Component)

My parent component goes like this :-

function UserList() {
/***/
return (
<>
<DataGrid>
</>

Child Component

function DataGrid() {
/***/
return (
<>
<FilterModal>
</>

Grand Child

function FilterModal() {
/***/
return (
<>
<LeftFilter>
</>

Requirement/To-Do :- I have a state value in LeftFilter, with that state I need to pass it to UserList and in change handler need to perform a filter operation with array of objects and append the state value. That updated state value will be append to in Parent component (UserList Component )

Upvotes: 0

Views: 74

Answers (1)

Firing Dev
Firing Dev

Reputation: 88

I see your requirements and your main issue is just the difficulty of data passing

That is why there is Context in react library.

You can fix this using context like this.

DataContext

const dataContext = createContext(your data);
export const useDataContext = () => useContext(dataContext);
export const DataContextProvider = ({ children }) => {
    const [data, setData] = useState(your data)
    const [filter, setFilter] = useState(your filter);

    const value = {
        data,
        filter,
        setData,
        setFilter
    }

    return <dataContext.Provider value={value}>
        {children}
    </dataContext.Provider>
}

And when you wrap your App component with this context,

<DataContextProvider>
  <App />
</DataContextProvider>

You can use those setFilter, setData function in any of your components.

const { setFilter, setData } = useDataContext();

Upvotes: 0

Related Questions