iamfredrik
iamfredrik

Reputation: 340

React component not rerender on state change

I'm rendering the following form component twice in an other component. Problem is that when I enter a value in one of the rendered forms, it doesn't update the placeholder of the other form. How do I get react to re-render component after state change so that both forms have the same placeholder value?

Here's a fiddle: https://jsfiddle.net/o4h5af4g/7/

import React, { Component } from 'react';

class LengthForm extends Component {
  constructor(props){
    super(props)
    this.state = {
      length:1
    };
  }

 handleChange(event) {
   this.setState({length: event.target.value});
 }

 render() {
    return (
      <div className="LenghtForm">
        <input name="length" onChange={this.handleChange.bind(this)} type="integer" placeholder={this.state.length}/>
      </div>
    );
  }
}

export default LengthForm;

Upvotes: 1

Views: 4909

Answers (1)

Ursus
Ursus

Reputation: 30056

I think you just missed to initialize the input (input's value property) with the value from your state. This should trigger the re-render

<input name="length" onChange={this.handleChange.bind(this)} 
   type="integer" placeholder={this.state.length}
   value={this.state.length} />

Another flaw in your code is the constructor. You should set props first thing.

constructor(props){ 
   super(props); 
   this.state = { length: 1 }; 
}

Upvotes: 2

Related Questions