I just started working with React, stuck on editing form. I need to prefill the inputs, but also to be able to edit it. If I put defaultValue, I can't put value on input element. At this moment I can type in inputs but I have to edit both fields(form has two fields) in order to save both values. How I am supposed to do it ?
Example: I have recipe name and ingredients, I open modal with edit form, it's prefilled, I add some ingredients but leave the name untouched. It saves:
{name: "", ingredients: ing1,ing2,newIngredient}
<form role="form">
<div className="form-group">
<label htmlFor={props.recipeName}>Recipe</label>
<input
type="text"
className="form-control"
defaultValue={props.recipeName || ''}
name="recipeName"
placeholder="Recipe name"
onChange={props.handleChange.bind(this)}/>
</div>
<div className="form-group">
<label htmlFor={props.recipeIngredients}>Ingredients</label>
<textarea
type="text"
className="form-control"
defaultValue={props.recipeIngredients || ''}
placeholder="Enter ingredients separated by commas..."
onChange={props.handleChange.bind(this)}
name="recipeIngredients"></textarea>
</div>
</form>
Store the values in the state. First, add them in the componentDidMount
method so you have them when you load the form component:
ComponentDidMount() {
const { recipeName } = this.props;
this.setState({ recipeName });
}
Then, the onChange
of each <input>
updates the state. So, you save the component's state whichever way you are saving your values now:
updateInputValue(e) {
const { target: {value} } = e;
this.setState({ recipeName: value });
}
<input
type="text"
className="form-control"
value={this.state.recipeName}
name="recipeName"
placeholder="Recipe name"
onChange={this.updateInputValue}/>
When you get to redux
I recommend using Redux Form
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With