Whymess
Whymess

Reputation: 717

Getting values from dropdown and inputs in react

I am trying to get values from all the inputs. I am able to get the input values from the inputs but not from the drop down the select tag.

What am I doing wrong?

class App extends Component {
  constructor(props){
    super(props)

    this.state = {
      contacts
    };
  }

  removeContact(id) {
     const removedID = contact => contact.id !== id;
     const updatedContacts = this.state.contacts.filter(removedID)
     this.setState({contacts: updatedContacts})
  }

   handleSubmit(e){
     e.preventDefault(e)
     const target = e.target;
     console.log(target.email.value)
     console.log(target.gender.value)

   }


  render() {
    return (
      <div className="App">
            <form onSubmit={this.handleSubmit}>
            <div>
              <label>
               First Name:
                 <input type="text" value={this.state.first_name} name="first_name" />
              </label>
            </div>
            <div>
              <label>
               Last Name:
                 <input type="text" value={this.state.last_name} name="last_name" />
              </label>
            </div>
            <div>
              <label>
               Email:
                 <input type="text" value={this.state.email} name="email"/>
              </label>
            </div>
            <div>
              <select value={this.state.gender} onChange={this.handleSubmit}> 
                  <option name="male"> Male</option>
                  <option name="female">Female</option>
              </select>
            </div>
            <input type="submit" value="Submit" />
          </form>

Upvotes: 1

Views: 22565

Answers (1)

Fabian Schultz
Fabian Schultz

Reputation: 18556

You set the value of the select to state, but don't change the state when a new value is selected. You need to setState once the value changes so that it's reflected in the DOM:

class Example extends React.Component {
  constructor() {
    super();
    this.state = { gender: "male" };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.setState({ gender: e.target.value });
  }

  render() {
    return (
      <select value={this.state.gender} onChange={this.handleChange}>
        <option name="male"> Male</option>
        <option name="female">Female</option>
      </select>
    );
  }
}

ReactDOM.render(<Example />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 3

Related Questions