Reputation: 1363
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>
Upvotes: 5
Views: 34645
Reputation: 1024
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
Upvotes: 7
Reputation: 1685
You would need to put the values of the passed in props into your initial state. You'd need to do this in your constructor.
Currently your state is only getting updated via change events, but the initial state is never set (Well probably anyway. I'm only guessing this because you haven't included your full code).
Upvotes: 0