The worm The worm - 11 days ago 5
React JSX Question

Passing props/state to/from parent component

So I have a parent component and a log in component.

I want the user to enter their details and then hit submit and then store/pass those details around so they can be used by other components.

how is this best done in React?

for example I have this input field inside my log in component

<p>
<input type="text" id="playerName" value={this.props.nameValue} onChange={this.props.handleNameChange}/>
</p>


Then I want to pass the value that is entered to the parent component

I have this function in my parent component:

handleNameChange(event){
this.setState({nameValue: event.target.value})
};


and in my return I have:

return (
<div>
<LoginPage handleClick={this.handleClick.bind(this)} handleNameChange={this.handleNameChange.bind(this)}/>
</div>
)


However, when I console.log(nameValue) I get undefined. any ideas? can add more code if necessary/relevant

Answer

From your example you never pass nameValue to the child component.

Updated your example of rendering the LoginPage, passing this.state.nameValue into the child component via props:

return (
  <div>
    <LoginPage
      handleClick={this.handleClick.bind(this)}
      handleNameChange={this.handleNameChange.bind(this)}
      nameValue={this.state.nameValue}
    />
  </div>
)
Comments