Lizz Parody
Lizz Parody

Reputation: 1765

Update the state from child to parent component in React

I have this constructor in my parent component

  constructor (props) {
    super(props)
    this.state = {
      owner,
      name: '',
      projectToAdd: this.props.defaultProject,
    }
  }

And the property projectToAdd is set to the value passed by props, I need to change this property of the state with the following function located in my child component:

  handleProjectSelection = (project) => () => {
    this.setState({
      projectToAdd: project.get('id')
    })
  }

This function is called when I click an element of a <li> tag in my child component:

  renderDropdown () {
    const { projects } = this.props
    const projectsList = projects.map((project) => (
      <li className='u-cursor--pointer u-padding-tiny u-font-size--12px'
        key={project.get('id')}
        onClick={this.handleProjectSelection(project)} >
        {project.get('name')}
      </li>
    ))
    return (
      <div>
        <ul className='c-folder-dropdown'
          name='projectList'
          form='start-retro-form'>
          {projectsList}
        </ul>
      </div>
    )
  }

How can I change the state from the child component to the parent component?

Upvotes: 0

Views: 84

Answers (1)

Dennie de Lange
Dennie de Lange

Reputation: 2934

Pass a change handler function prop from your parent to the child.

class Parent{
   handleChange = () => {
      this.setState({
        foo: 'bar'
      })
    }

   render(){
      return <Child onChange={this.handleChange} {...this.state}/>
   }
}

Upvotes: 1

Related Questions