polar
polar

Reputation: 522

Update input value from state not working

Im encountering an issue where inputs, and in this case select input is not updating when state is updated. Can anyone tell me where I'm going wrong here?

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        selectType:'1'
    }
   }

    onChangeEndpointType(event) {
        this.setState=({
          selectType:event.target.value, 
        })
    }

    render() {
        return (
            <select name="selecttype" value={this.state.selectType} onChange={() => this.onChangeEndpointType(event)}>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
            </select>
        )}
  }

Upvotes: 1

Views: 64

Answers (3)

reachtokish
reachtokish

Reputation: 356

You have couble of bugs in your code

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectType:'1'
    }
  }

  onChangeEndpointType(event) {
    this.setState({
      selectType:event.target.value, 
    })
  }
  render() {
    return (
      <div className="App">
        <select name="selecttype" value={this.state.selectType} onChange={(event) => this.onChangeEndpointType(event)}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
        </select>
      </div>
    );
  }
}

One is setState syntax error

this.setState({
  selectType:event.target.value, 
})

Another one is you have pass event in the onChange callback

onChange={(event) => this.onChangeEndpointType(event)}

Upvotes: 0

Syed Khizaruddin
Syed Khizaruddin

Reputation: 435

you have to bind this of function with this of constructor: vote if it works

class Page extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        selectType:'1'
    }
    this.onChangeEndpointType = this.onChangeEndpointType.bind(this);
}

    onChangeEndpointType(event) {
        this.setState=({
        selectType:event.target.value, 
        })
    }

    render() {
        return (
            <select name="selecttype" value={this.state.selectType} onChange={() => this.onChangeEndpointType(event)}>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            </select>
        )}
}

Upvotes: 0

German
German

Reputation: 557

I believe the setState has a typo, try this:

 onChangeEndpointType(event) {
     // setState 
     this.setState({
       selectType:event.target.value, 
     })
    }

Upvotes: 1

Related Questions