My state is
const [ formInputsProperty, setFormInputsProperty ] = useState(
[
{
id: 0,
name: "courseTitle",
type: "text",
placeholder: "Course Title",
errorMessage: "Course Title should be 3-16 characters and shouldn't include any special character!",
label: "Course Title",
pattern: "^[A-Za-z0-9]{3,16}$",
required: true,
isFocused: false
},
{
id: 1,
name: "shortDesc",
type: "text",
placeholder: "Course Short Description",
errorMessage: "Course Description should be 10-50 characters and shouldn't include any special character!",
label: "Course Short Description",
pattern: "^[A-Za-z0-9]{10,50}$",
required: true,
isFocused: false
}
]
)
Now i want to update isFocused to true of all elements of the given state. How can I do that? I tried map but was not successfull.
CodePudding user response:
You can do it by using the map function and then setting the state afterwards.
Example:
const updateFocus = () => {
setFormInputsProperty((prev) => (
prev.map((item) => ({...item, isFocused: true}))
);
};
Explanation:
You access the current state with prev
and then use the map
function on it. With map
you iterate over every element in the list and can do what ever you want with it. In this case we just set the isFocused
property to true. The return value inside the map
function always replaces the current item.