I'm currently building a form with React, and I'm wondering what the best practices are for pre-filling fields from an object.
import React, { Component } from 'react' class EditResourceForm extends Component { constructor (props) { super(props) this.state = { resource: props.resource } } handleFieldChanged (e) { // update state } render () { return ( <input type="text" value={this.state.resource.email} onChange={::this.handleFieldChanged} /> ) } } I'm encountering a problem when this.state.resource.email is null or undefined, because React does not want me providing those as values to controlled components:
Warning: `value` prop on `input` should not be null. Consider using the empty string to clear the component or `undefined` for uncontrolled components. Where is the proper place to provide an empty string as a fallback for a null value? Should this be done in the parent component's constructor method? Is there a way to avoid having to do this explicitly for every attribute that might have a null value?
resource: props.resourcetoresource: props.resource || {}so it doesn't throw an error if props.resource is empty.