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
- Declare a state and a setter for the title or slug
- Define a function to update the state
- 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
- Define a button etc. with an onClick event
- 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 !!!
1 Like
for some reason when i try it nothing happens when i click the button