Ozge Cokyasar
Ozge Cokyasar

Reputation: 313

How can I pass a parent's state to be used within a child component?

I have a parent component where I am looping through an array and setting the state for clicked to that of the id of the clicked item in the array.

I am using this component elsewhere where I need to access this state. How can I go about passing this state down?

Here is my loop:

{
 filteredArray.map(link => {
  return (
   <div
   key={link.id}
   role="button"
   style={{paddingBottom: 20}}
   onClick={this.changeView(link.id)}
   onKeyPress={() => {}}
   tabIndex={0}
  >
  <Paragraph size="large">
    <a className='heading__dropdown__link'>
     {link.label}
    </a>
  </Paragraph>
 </div>
)
})
}

Here is my function where I am setting the state for clicked

  changeView(id) {
    return (
      () => this.setState({clicked: id})
    )
  }

And here is where I am using the above component: How can I use the above state here?

 <HeadingDropdown
  expandedTitle="Change view"
  links={links}
  heading={currentLocation}
 />

Upvotes: 0

Views: 118

Answers (1)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

Working off your last comment. If you passed down a function to be used as a prop in HeadingDropdown, you can use it to pass back up it's state-value to the Parent.

Function defined in Parent

class Parent extends React.Component{
   state = {
     headingDropdownvalues: {}
   }

   getHeadingDropdownState = (valueFromChild) => {
      this.setState({
         headingDropdownvalues: valueFromChild
      })

   }

   render(){
      <HeadingDropdown passupstate={this.getHeadingDropdownState}/>
   }
}

So now your parent component is set-up to consume the state-value from HeadingDropdown.

Now we need to configure HeadingDropdown to actually pass up that value after clicking.

In HeadingComponent, we just need to update your changeView method to call the prop we passed down, after the state has been set. We do this by utilizing the 2nd argument of this.setState() which is a call-back.

changeView(id) {
    return (
      () => this.setState({
        clicked: id
      }, () => this.props.passupstate(this.state)) //right here you can pass in whatever you want
    )
  }

Also here is a sandbox for you to see how it works: https://codesandbox.io/s/jovial-thompson-ldg3n

Upvotes: 2

Related Questions