Use Forms To Add An Item#
Add The Form#
To be able to add FAQ items to the list, we will start by adding an add form:
23return (
24 <div>
25 <ul>
26 {faqList.map((item, index) => (
27 <FaqItem
28 key={index}
29 question={item.question}
30 answer={item.answer}
31 index={index}
32 onDelete={onDelete}
33 />
34 ))}
35 </ul>
36 <form>
37 <label>
38 Question: <input name="question" type="text" />
39 </label>
40 <label>
41 Answer: <textarea name="answer" />
42 </label>
43 <input type="submit" value="Add" />
44 </form>
45 </div>
46 );
Manage Field Values In The State#
To manage the values of the fields in the form, we will use the state.
Add a question and answer value to the state which contains the values of the inputs.
Add onChange
handlers to the input and textarea which will change the values in the state when the input changes.
This pattern is called "controlled inputs".
Submit Handler#
Now that our values are managed in the state, we can write our submit handler.
Write an onSubmit
handler which reads the values from the state and adds the new FAQ item to the list.
After the item is added, the inputs should also reset to empty values.