Ad
Why Won't My Controlled Input Component In React Update With The State?
I've got a list of ingredients in an "editIngreds" array in my state, e.g. ['Apple', 'Banana', 'Orange']. They are rendered to the DOM via react map function. I have an edit mode that replaces the text with Input boxes so I can edit the items and save them back to the state array. However, when typing in the box, nothing happens. console.log shows that editIngreds[i] is indeed being updated when I type a character, however the input boxes do not update with this new value.
export default function RecipeCard({ recipe, onEditRecipe, onRemoveRecipe }) {
const ingredients = Object.values(recipe.ingredients);
const ingredientKeys = Object.keys(recipe.ingredients);
const [editIngreds, setEditIngreds] = React.useState(ingredients)
...
const onChangeEditIngreds = (event, i) => {
const value = event.target.value;
const ingreds = editIngreds
ingreds[i] = value;
setEditIngreds(ingreds);
};
...
return (
<ul>
{ingredients.map((ingred, i) => (
<li key={ingredientKeys[i]}>
{editMode ? (
<Input
type="text"
value={editIngreds[i]}
onChange={(e) => onChangeEditIngreds(e,i)}
/>
) : (
<>{ingred}</>
)}
</li>
))}
</ul>
Ad
Answer
You are mutating the state
. Make a shallow copy of ingredients
before updating
const onChangeEditIngreds = (event, i) => {
const value = event.target.value;
const ingreds = [...editIngreds];
ingreds[i] = value;
setEditIngreds(ingreds);
};
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad