Adding Items from a Form

Forms often add something to a list: a comment, a task, a thing to pack. You know both halves already. What's typed is in the state of a controlled field, and the State lesson showed you how to add to an array in state: with a new array, made with spread in an updater function. The form's handler puts them together:

function handleSubmit(event) {
    event.preventDefault();
    setWishes((wishes) => [...wishes, { id: Date.now(), band: band }]);
    setBand("");
}

That's from a form where fans suggest bands for next year. The new wish goes to the end of a new array, and it gets an id for its key. Date.now() is the number of milliseconds since the start of 1970, so it's a different number each time someone adds a wish, which is good enough for an id here. Then setBand("") empties the field, so the next band can be typed right away. With a controlled field, emptying it is just a change of its state.

An empty wish makes no sense, so the button shouldn't work while the field is empty. The attribute disabled takes a condition:

<button type="submit" disabled={band.trim() === ""}>
    Suggest
</button>

While the condition is true, the button is disabled: it looks paler, and clicking it does nothing. With only spaces in the field, trim() gives "", so it stays disabled. A form whose submit button is disabled can't be sent with Enter either. And because every render works the condition out again from the state, the button comes alive with the first letter typed.

Instructions

When the form is sent, add what's typed in the field to the end of the list, as a new item with an id, and empty the field.

Disable the button Add while the field is empty or has only spaces in it.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

7/9

Next