Text Areas and Drop-Down Lists

Other fields work the same way: the state holds their value, they show it, and onChange changes it. Two of them are written a little differently in React than in HTML.

A textarea, the field for longer text, has its text between its tags in HTML. In React, it gets value, as an input does, and closes itself:

<textarea
    id="note"
    value={note}
    onChange={(event) => setNote(event.target.value)}
/>

A select gets value too. In HTML, the attribute selected chose an option in advance. In React, the state says which option is chosen, as the value of the select:

const [drink, setDrink] = useState("coffee");

return (
    <select value={drink} onChange={(event) => setDrink(event.target.value)}>
        <option value="tea">Tea</option>
        <option value="coffee">Coffee</option>
        <option value="juice">Juice</option>
    </select>
);

When the app starts, the state is "coffee", so Coffee is chosen. When the user chooses Tea, event.target.value is "tea", the value of that option, and that goes into the state.

The options often come from data. In this exercise, the tickets are an array, and the select makes an option of each one with map(). The state keeps only the id of the chosen ticket. To show its name and price, find it in the array, in the component's function before return:

const chosen = tickets.find((ticket) => ticket.id === ticketId);

Each render finds the ticket that the state names, so the ticket below the form always matches the select.

Instructions

Make the ticket select controlled with a state variable ticketId that starts as "weekend". Find the chosen ticket in tickets, and show its name in ticket-type and its price in ticket-price, for example Friday and €45.

Make the gift message (textarea) controlled with a state variable giftMessage, and show the message on the ticket, in ticket-gift.

Start programming for free

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

Or sign up with:

Back

3/9

Next