0
votes

I am trying to pass an input value for a form between 2 different react classes. The code below is working. The user types in their name to the form, click submit. they jump to a new view and the name they typed in is stored in state and can be retrieved as a prop. This works

<form onSubmit={this.handleClick}>
            <input type="text" id="playerName" value={this.state.name} onChange={this.handleChange} placeholder="name" />
            <input type="submit" value="submit" />
          </form>

if (this.state.results){
      output = <Decision name={this.state.value}/>;
    }

handleChange: function(event){
    this.setState({name: event.target.value})
  },

My problem is that I want to to know add a new input type to the form. this time email. However I cannot seem to replicate it with the same logic as I keep making errors.

 if (this.state.results){
          output = <Decision name={this.state.value} email={this.state.value}/>;
        }

I tried adding a new prop (above) but when ever I typed in to the name field, this would also enter text into the email field (probably because I am updating the same state). How can I create an email prop and store and retrieve the state of this? Can props be as simple as email={this.state.email}?

1

1 Answers

0
votes
if (this.state.results){
      output = <Decision name={this.state.value} email={this.state.value}/>;
    }

Here, you are using value for both name and email from a single state: value.

You need to declare an extra state to manage email change. This will look something like this:

this.state = {
  nameValue: '',
  emailValue: '',
};

Then you will also need two different methods for handleChange. Something like, handleNameChange and handleEmailChangewhich will look like this:

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

 handleEmailChange(event) {
  this.setState({emailValue: event.target.value});
}

Then your inputs will change like this:

 <form onSubmit={this.handleSubmit}>
    Name: <input type="text" value={this.state.nameValue} onChange={this.handleNameChange} />
    Email: <input type="email" value={this.state.emailValue} onChange={this.handleEmailChange} />
    <input type="submit" value="Submit" />
  </form> 

At last, you can pass new email as a prop like this:

if (this.state.results){
      output = <Decision name={this.state.nameValue} email={this.state.emailValue}/>;
    }

here's a working example on codepen