user3226524
user3226524

Reputation: 103

How to pass form data from child component to parent component

I want to send the form data which is in my child to parent component. On submit function I have written in Parent component. Parent Component :

    handleChangeValue = (e) => {
      this.setState({
        [e.target.name]: e.target.value,
        [e.target.value]: e.target.value
     });
   }

   handleSubmit() {
      var newObj = {
      'id' : this.state.id,
      'name' : this.state.name,
   };

   render() {
     return (
       <div className="App">
        <UsingForm onChangeValue = 
         {this.handleChangeValue} handleSubmit = {this.handleSubmit}> 
         </UsingForm>
      </div>
     );
   }

And Child component is:

 <form onSubmit={this.handleSubmit}>
     <label>
      Name:
        <input type="text" name="uname" value = {this.props.uname} 
        onChange={(e)=>this.props.onChangeValue(e)}></input>
     </label>
     <label>
     ID:
      <input type="text" name="id" value = {this.props.id} onChange= 
       {(e)=>this.props.onChangeValue(e)}></input>
      </label>
      <input type="button" value="Submit" onClick= 
      {this.props.handleSubmit} />
 </form>

Not getting state values in handleSubmit(), why?

Upvotes: 0

Views: 1321

Answers (2)

Shanti Swarup Tunga
Shanti Swarup Tunga

Reputation: 641

You have to change

<label>
  Name:
    <input type="text" name="name" value = {this.props.name} 
    onChange={(e)=>this.props.onChangeValue(e)}></input>
 </label>

and

<UsingForm onChangeValue = 
     {this.handleChangeValue} handleSubmit = {this.handleSubmit} name={this.state.name} id={this.state.id}> 
</UsingForm>

Upvotes: 0

kkangil
kkangil

Reputation: 1746

you have to bind handleSubmit function using arrow function

handleSubmit = () => {
      var newObj = {
      'id' : this.state.id,
      'name' : this.state.name,
      };

or in constructor

constructor(props) {
  ...
  this.handleSubmit.bind(this)
}

Upvotes: 2

Related Questions