JohnnyQ JohnnyQ - 3 months ago 11
React JSX Question

ReactJS how to allow changes on an uncontrolled input?

I have a have a Component that generates text inputs with these conditions:


  • I want to initialize it with a value

  • Should be uncontrolled



I tried
defaultValue
but it affects the next Components created wherein the value stays the same for succeeding inputs. I also tried
value
but it gives me an error saying I should include an
onChange


So here is currently the display of my table component

enter image description here

Each row is represented by the Component below:

var ScheduleResultRow = React.createClass({
render: function() {
return(
<tr>
<td><input type="text" value={this.props.slot.date} /></td>
<td><input type="text" value={this.props.slot.day} /></td>
<td><input type="text" value={this.props.slot.time} /></td>
<td><input type="text" value={this.props.players.player1 + " - " + this.props.players.player2} /></td>
<td><input type="text" value={this.props.slot.field} /></td>
</tr>
)
}
});


As you can see the value is generated by it's parent Component transferred through
props
. I don't want to keep a state of the rows because it's just for display purposes and it's just a calculated from the state of its parent.

Any idea how do I achieve this? Any help would be very much appreciated.

Answer

Use componentDidMount method: Initialize textboxes when they are added to DOM:

var ScheduleResultRow = React.createClass({
componentDidMount: function (){
   this.refs.date.value = this.props.slot.date;
   this.refs.day.value = this.props.slot.day;
   this.refs.time.value = this.props.slot.time;
   this.refs.player2.value = this.props.players.player1 + " - "     + this.props.players.player2;
   this.refs.field.value = this.props.slot.field;
}
render: function() {
    return(
        <tr>
            <td><input type="text" ref="date"/></td>
            <td><input type="text" ref="day"/></td>
            <td><input type="text" ref="time"/></td>
            <td><input type="text" ref="player2"/></td>
            <td><input type="text" ref="field"/></td>
        </tr>
    )
  }
});