Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138192

Unable to change dropdown value in React child component

$
0
0

I have two two components:

App component:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedScale: "WholeTone"
    };
    this.handleScaleSelect = this.handleScaleSelect.bind(this);
  }

  handleScaleSelect = selectedScale => {
    console.log("ss: " + selectedScale);
    console.log(this.state);
    this.setState({ selectedScale: selectedScale });
    console.log("after ss:" + this.state.selectedScale);
  }

  render() {
    return (
        <Scales
          onSelectScale={this.handleScaleSelect}
          selected={this.state.selectedScale}
        ></Scales>
    )

Scales component:

class Scales extends Component {
  state = {
    options: []
  };
  constructor(props) {
    super(props);
    // this.getScales();
  }

  render() {
    return (
      <form onSubmit={() => this.props.onSelectScale(this.getSelectedScale())}>
        <select id="scaleSelectId"></select>
        <input type="submit" value="render scale" />
      </form>
    );
  }

  componentDidMount() {
    var xhr = new XMLHttpRequest();
    function addOptions() {
      var select = document.getElementById("scaleSelectId");
      JSON.parse(xhr.responseText).map(scale => {
        var option = document.createElement("option");
        option.text = scale;
        select.add(option);
      });
      select.value = this.props.selected;
    }
    xhr.open("GET", "http://127.0.0.1:5000/get_scales");
    xhr.onload = addOptions.bind(this);
    xhr.send();
  }
}

I want to change dropdown value, press form's submit button and pass that value to the parent element so it is used further. I wonder what am I doing wrong. I did some logging in handleScaleSelect to see what's going on, and weirdly - the selectedScale variable is equal to the submitted value, but the state of component is not altered.


Viewing all articles
Browse latest Browse all 138192

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>