How to create managed input with an empty default value in React 15

I have a problem with text input that I want to control, but it must support an empty value. Here is my component:

import React, { Component, PropTypes } from 'react'; import { ControlLabel, FormControl, FormGroup } from 'react-bootstrap'; const propTypes = { id: PropTypes.string.isRequired, label: PropTypes.string, onChange: PropTypes.func, upperCaseOnly: PropTypes.bool, value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; export default class UppercaseTextField extends Component { constructor(props) { super(); this.state = { value: props.value }; this.onChange = () => this.onChange(); } onChange(e) { let value = e.target.value; if (this.props.upperCaseOnly) { value = value.toUpperCase(); } this.setState({ value }); this.props.onChange(e); } render() { return ( <FormGroup controlId={id}> <ControlLabel>{this.props.label}</ControlLabel> <FormControl type="text" onChange={this.onChange} defaultValue={this.props.value} value={this.state.value} /> </FormGroup> ); } } UppercaseTextField.propTypes = propTypes; 

When this is initially set, props.value is usually (though not always) set to. '' This makes React 15 unhappy since value = '' causes the value to be discarded, so React considers it an uncontrolled input, even if it has onChange.

The component works, but I do not like to receive this warning in the console:

Note: FormControl changes the controlled input of text of a type that will be uncontrolled. Input elements should not switch with uncontrolled (or vice versa). Decide using an uncontrolled input element for the component lifetime. More info: http://facebook.imtqy.com/react/docs/forms.html#controlled-components

This worked fine in 0.14.x without any warnings, but now 15 doesn't seem to like it. How to clean it in order to maintain functionality, but get rid of the warning?

+8
reactjs react-bootstrap
source share
1 answer

ensure this.state.value not undefined on mount. You can do this in your constructor by setting this.state = {value: props.value || ''}; this.state = {value: props.value || ''}; or by making props.value required property.

+10
source share

All Articles