Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, {Component};
- class ParentComponent extends Component {
- //Initial State
- state = { data: [] }
- //Function to update the state
- //NOTE-1: You only can use this.setState to update the state
- //NOTE-2: You never want to update your state directly that why I use .concat instead of .push.
- addElementIntoState = (element) => {
- this.setState({data: this.state.data.concat(element)})
- }
- render(){
- return (
- // Passing the callback function via props into child
- // Each time the child executes this function the parent will know that its state is being updated.
- // And will re-render with the new state.
- <MyChild addElementIntoState={addElementIntoState}>
- )
- }
- }
Add Comment
Please, Sign In to add comment