Ad

React Controlled Components Not Receiving Inputs Properly

- 1 answer

I can't figure out Controlled Components. Doing everything almost exactly as in the example in the docs: https://facebook.github.io/react/docs/forms.html#controlled-components .

What happens is only one input character gets into the input. Upon the next character entry, the previous one gets replaced. When I enter 'asdf', I get this:

changeName a
changeName s
changeName d
changeName f

Here's my code:

export class MyComponent extends Component {
  constructor(props) {
    super(props)
    this.handleChangeName = this.handleChangeName.bind(this)
    this.handleChangeDescription = this.handleChangeDescription.bind(this)
    this.state = ({name:'',description:''})
  }

  shouldComponentUpdate (nextProps, nextState) {
    return false
  }

  handleChangeName(event) {
    console.log('changeName',event.target.value)
    this.setState({name: event.target.value.substr(0, 8)});
  }

  handleChangeDescription(event) {
    this.setState({description: event.target.value.substr(0, 140)});
  }

  render () {
    return (
    <Row>
      <Col xs={12} lg={12} className="beacon-fields">
        <Input id="name" help="Name" className="form-control" type="text" value={this.state.name} onChange={this.handleChangeName} />
        <Input id="description" help="Description" className="form-control" type="text" value={this.state.description} onChange={this.handleChangeDescription} />
      </Col>
    </Row>
  )
}

What am I doing wrong?

Ad

Answer

The issue was rather obvious. shouldComponentUpdate method prevented the render from executing, which means the inputs was not appearing in the input fields. The solution was rather simple:

shouldComponentUpdate (nextProps, nextState) {
  if (this.state !== nextState) {
    return true
  }    
  return false
}
Ad
source: stackoverflow.com
Ad