Child Component Updating Parent State



Can anyone help me with updating parent state from child to parent in React?

I am trying to update parent state (App) from child component (Layout) which has a subcomponent imported called .

Basically, I want to update parent state (App) with the chosen page in the child component (Layout). Layout has imported a bunch of child components, and one of them is

I need ListItem to update, onClick, parent state in App.

How do I Do that?

Hi Adam,
I can’t read all of your question. Parts of your text (code) has been swallowed due to a lack of formatting. What I see from your screenshots is that you’re using functional components and no Redux, right? Then this is the way:

Parent component

  1. Declare a state and a setter for the title or slug
  2. Define a function to update the state
  3. Pass that function down as props to the child component
const [currentPage, setCurrentPage] = useState('');
const updatePage = title => {
   setCurrentPage(title)
}
return (<div>
  //... some parent component code
  <ChildComponent updatePage={updatePage} />
</div>)

Child Component

  1. Define a button etc. with an onClick event
  2. Define a function that handles the click and calls the function passed as props from the parent component
export const ChildComponent = ({updatePage}) => {
  const title = 'Current Article Title';
  const handleClick = () => {
    updatePage(title)
  }
  return (<div>
    //... some child component code
    <button onClick={handleClick} >{title}</button>
  </div>)
}
1 Like

Excellent! This worked :smiley: !!!

1 Like

for some reason when i try it nothing happens when i click the button