Part 1: Adding A Form

Forms are used everywhere in websites. Now let's make one using React!

Let's start off simple. Navigate to BookForm.tsx and create the form.

Writing the Form

Here's some code. Go ahead and figure out where to put this

<form className="book-form" onSubmit={handleSubmit}>
    <div>
        <label htmlFor="title">Title:</label>
        <input
            type="text"
            id="title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
        />
    </div>
    <div>
        <label htmlFor="author">Author:</label>
        <input
            type="text"
            id="author"
            value={author}
            onChange={(e) => setAuthor(e.target.value)}
            required
        />
    </div>
    <button className='button' type="submit">Add Book</button>
</form>

Form submission logic

Let's work on the form submission logic. Look at const handleSubmit, which is the function that allows us to submit the form's data using a POST request. Here's some skeleton you can use to fill out the block. Make sure to replace all the // YOUR CODE HERE.

If you are stuck, try to use Postman's JavaScript -- Fetch generation method to reference what the code should look like.

try {
    await fetch('<API ENDPOINT HERE>', { // YOUR CODE HERE
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ key1, key2 }), // YOUR CODE HERE: REPLACE KEY1, KEY2
    });
    setTitle('');
    setAuthor('');
    alert(); // YOUR CODE HERE
} catch (error) {
    console.error(); // YOUR CODE HERE
    alert(); // YOUR CODE HERE
}

Styling the Form

You may have noticed that the form looks... pretty bad! Here's the last challenge to the assignment. You should do the following:

  1. Style the form so it has a consistent background, text styling, button styling, etc.

  2. Add placeholder text for each of the fields. Here's an example of placeholder text:

  1. Challenge: Make this form pop up as part of a modal. A modal is basically a pop up window. The workflow would look something like this:

    1. The main page has a button labelled "Add Book."

    2. Clicking the buttom should open a modal that has two fields: title and author

    3. On successful submit, the modal should close and you should see another "success" popup on your page that remains there for 1 second.

There's purposefully no guidance for this part. You are free to Google, ChatGPT, or use whatever resources to complete this part.

Last updated