1

I have a UserModal which is both used for insert and editing a user. On my <input> element I have both specified the value prop which uses the state and the defaultValue prop which uses the username props if it is not null.

<input
  type="text"
  className="form-control"
  id="username"
  tabIndex={1}
  required={true}
  onChange={this.handleOnUsernameChange}
  value={this.state.username}
  defaultValue={this.props.username || ''} />

UserModal contains an input of type number with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props.

If I use the <input> element snippet from above then I get the warning/error message printed in the console. What are the best practices for handling situations where the default value is required with controlled component? Or is it easier/better to do this with an uncontrolled component?

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
tomwassing
  • 925
  • 1
  • 10
  • 30

1 Answers1

0

Use a controlled component. You can set your default prop in the state.

this.state = {
   username: this.state.username || this.props.username
};

this.onChange = this.handleOnUsernameChange.bind(this);

<input
   type="text"
   className="form-control"
   id="username"
   tabIndex={1}
   required={true}
   onChange={this.handleOnUsernameChange}
   value={this.state.username}
/>

handleOnUsernameChange = e => {
   this.setState({
      username: e.target.value
   });
   console.log(e.target.value);
}
Paul Redmond
  • 3,276
  • 4
  • 32
  • 52
  • Initializing the state based on the props is a anti-pattern; https://medium.com/@justintulk/react-anti-patterns-props-in-initial-state-28687846cc2e – tomwassing Aug 24 '18 at 10:52
  • Interesting... personally I never encountered a problem this way. Might be because it's being used to set the initial value if there's no value in the state. In this case I don't think there's going to be a side effect as the component is not relying on the prop to perform anything other than display the initial value. – Paul Redmond Aug 24 '18 at 10:57
  • https://stackoverflow.com/questions/40063468/react-component-initialize-state-from-props – Paul Redmond Aug 24 '18 at 11:12