Skip to content
Advertisement

Why does the state variable become undefined when the value is changed in the dropdown menu react?

Here is the table I’m trying to create:

enter image description here

When I change the value of the dropdown bars, the value becomes undefined and I don’t understand why. But initially, when I click submit, it works and the alert pops up with both of the default values I set in this.state.

This is what the alert looks like when I change the SDG:

enter image description here

Here is the code:

import React from 'react'

class Dropdown extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        sdg: 'SDG 1: No Poverty',
        assignment_type: 1
    };
  
      this.handleSDGChange = this.handleSDGChange.bind(this);
      this.handleAssignmentChange = this.handleAssignmentChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }
    
    // Handling all 3 input changes
    handleSDGChange(event) {
      this.setState({sdg: event.target.sdg});
    }

    handleAssignmentChange(event) {
        this.setState({assignment_type: event.target.assignment_type});
    }

    // Handling all 3 input submissions
    handleSubmit(event) {
        console.log(this.state.sdg)
      alert(this.state.sdg + '--- Assignment Type: ' + this.state.assignment_type);
      event.preventDefault();
    }

    render() {
      return (
        <form onSubmit={this.handleSubmit}>
            <label>SDG:</label>
            <select value={this.state.sdg} onChange={this.handleSDGChange}>
              <option value="SDG 1: No Poverty">SDG 1: No Poverty</option>
              <option value="SDG 2: Zero Hunger">SDG 2: Zero Hunger</option>
              <option value="SDG 3: Good Health & Well Being">SDG 3: Good Health & Well Being</option>
            </select>

            <label>Assignment Type:</label>
            <select value={this.state.assignment_type} onChange={this.handleAssignmentChange}>
              <option value="1">1: Discussion Project</option>
              <option value="2">2: PDF Case study</option>
              <option value="3">3: Community Project</option>
            </select>

            <input type="submit" value="Submit" />
        </form>
      );
    }
  }
export default Dropdown

Advertisement

Answer

You want to change your event.target.sdg and event.target.assignment_type to event.target.value. event.target does not have those properties, those are simply the variables you defined in your this.state, if you want to access the value of the event of each of the handlers, you use .value.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement