Home > Mobile >  How to access data of Child Component from parent component in react js
How to access data of Child Component from parent component in react js

Time:09-28

I am doing a project where i have a toast function which implements toast there i call the function of fetching data from api and updating my state so that whenever i click the update feed button fetching data from api function called, updation of state and toast of success appears. Now the question is i have a component of categories post displays seperate category post inside of all post component which has the function to display toast, how could i pass the updated state,fetching data from api function from child component that is category post component to parent component that is all post component to implement toast for category component.

CodePudding user response:

this is a good article that explains what you want here

CodePudding user response:

If I understand your question correctly -- at a high level, you're trying to figure out how to update a state variable of a parent component from within a child component. Easiest way would be with the useState hook, and then passing the setState function to the child component.

const ParentComponent = () => {
  const [state, setState] = useState()

  return <ChildComponent setState={setState} />
}

const ChildComponent = ({setState}) => {
  return <Button onClick={() => setState('I was clicked! Update parent state')} />
}

CodePudding user response:

There are two ways I can think of to achieve what you are trying to do here, i.e. get the child component's state in a parent component.

  1. You can make use of refs. You should be familiar with React hooks to use this approach. The documentation is really good.
  2. You can also make use of a global state using either Redux or Context.
  • Related