Solution to the Exercise

Learn more about the nuances of testing and fix the failing test from the last lesson.

We'll cover the following

Solution

As you recall, we wrote a test that renders the TaskInput component. We also tried entering some text into it. It then validated that an onSubmit callback was called.

Firstly, we need somewhere to store the input value. Let’s use the state for that:

const [value, setValue] = useState('');

And the handler function for the input:

const handleChange = (event) => setValue(event.target.value);

Now, we need to connect these to the input:

<input
  type={'text'}
  placeholder={'Enter new task'}
  value={value}
  onChange={handleChange}
/>

Almost done! The trick is to capture the “enter button press” to submit. Let’s create a handler for that:

const handleSubmit = (event) => {
        event.preventDefault();
        onSubmit(value);
    };

The onSubmit is the prop that you need to unpack in the component definition: const TaskInput = ({onSubmit}). We are almost there! But where does the handleSubmit plug in? Unfortunately, input does not have a default way to capture an “enter press” without excessive complications. To simplify our lives, wrap the input in the form element:

<form onSubmit={handleSubmit}>
  <input
    type={'text'}
    placeholder={'Enter new task'}
    value={value}
    onChange={handleChange}
  />
</form>

Here is the completed project (try running the tests now!):

Get hands-on with 1400+ tech skills courses.