Controlled Forms in React Lab Exercise

Introduction

In this lab, you’ll explore practical applications of React’s state management through controlled forms. You’ll build a dynamic form that allows users to add entries to a virtual bookshelf, practicing the synchronization of UI and state in React to ensure seamless user interactions.

What you’ll build

The local library is adding a feature to its website where users can add their favorite books to a virtual bookshelf.

You will develop a single component named BookShelf that contains both the controlled form and the display of the bookshelf. Using the useState hook, you will manage the form inputs and list of books, enabling real-time updates to the UI based on user input.

Solution UI

By the end of this lab, you’ll have a functional application where users can add books to a personalized bookshelf, with each new entry updating the display immediately—no page reloads required!

Lab exercises

1. Create your component

Create a new component called Bookshelf:

mkdir src/components
mkdir src/components/Bookshelf
touch src/components/Bookshelf/Bookshelf.jsx

Import useState at the top of the file:

import { useState } from 'react';

Use the following template to set up your BookShelf component:

<div className="bookshelfDiv">
  <div className="formDiv">
    <h3>Add a Book</h3>
    {/* Form will go here */}
  </div>
  <div className="bookCardsDiv">{/* Book cards will display here */}</div>
</div>

Export Bookshelf from this file and import it into App.jsx:

// src/App.jsx
import './App.css';
import Bookshelf from './Bookshelf.jsx';

const App = () => {
  return (
    <>
      <h1>My Bookshelf</h1>
      <Bookshelf />
    </>
  );
};

export default App;

The remainder of the work in this lab will all take place inside Bookshelf.jsx.

2. Define the initial state

Initialize your state in Bookshelf.jsx:

Example:

const [books, setBooks] = useState([
  { title: 'Fourth Wing', author: 'Rebecca Yarros' },
  { title: 'The Lion, the Witch and the Wardrobe', author: 'C.S. Lewis' },
]);

3. Create event handlers

For this lab, you’ll need two event handlers:

a. handleInputChange

Purpose: This function updates the form’s state as the user types into the input fields.

Instructions:

b. handleSubmit

Purpose: This function manages the submission of the form, adding a new book to the list, and resetting the input fields.

Instructions:

4. Form creation

5. Map through your books