The worm
The worm

Reputation: 5888

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

Upvotes: 1

Views: 119

Answers (2)

Michael S
Michael S

Reputation: 425

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>
)

Upvotes: 1

Alex Young
Alex Young

Reputation: 4039

Your approach using state and props is fine. Are you sure that you shouldn't just be using...

console.log(this.state.nameValue);

This is a working example

class Parent extends React.Component {
    constructor() {
        super();
        this.state = {
            nameValue:''
        };
    }
    render() {
        return (
            <Child handleClick={this.handleClick.bind(this)} handleNameChange={this.handleNameChange.bind(this)} nameValue={this.state.nameValue} />
        );
    }
    handleNameChange(e) {
        this.setState({
            nameValue: e.target.value
        });
    }
    handleClick() {
        alert(this.state.nameValue);
    }
}

class Child extends React.Component {
    render() {
    return (
        <div>
            <input type="text" value={this.props.nameValue} onChange={this.props.handleNameChange} />
          <button onClick={this.props.handleClick}>Click Me!</button>
        </div>
    );
  }
}

JSFiddle here.

Upvotes: 1

Related Questions