This video is available to students only

How to Submit New Items on Enter With React onKeyPress

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

Previous LessonHow to Automatically Focus on Input Fields With React refsNext LessonA useReducer Guide: How to Add Interactivity With React Context

Lesson Transcript

  • [00:00 - 01:49] Submit on enter. Let's make the new item form component to submit the input on enter keypress as well so that the items could be created either by pressing the create button or by pressing the enter key. To do this we're going to add an on keypress handler to the text input in the new item form component. Inside of the new item form create a function handle add text is going to process an event of type react keyword event and the type of the event is going to be HTML input element because we know we're gonna listen to this event on the input. Inside of this function we check if event key is enter we call on add from the props and passing the text from the state. Now we can add an on keypress to a new item input here we pass the handle add text and that's it. Here we use the keyword event from react you can find all the available event types in the react documentation and types for them in react type definitions. Right now we already passed their on add callback to add new item and it's gonna end up in the new item form so if you launch the application and try to add new list test list and then press enter you should see the log with the text you've passed to this form. By the way if you pass console log directly here and then try to do the same test test log you won't see any logs so make sure to wrap your console log into a function. This is happening because react overrides the the fault console lock behavior when rendering your components.

This lesson preview is part of the Fullstack React with TypeScript Masterclass course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

Unlock This Course

Get unlimited access to Fullstack React with TypeScript Masterclass, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course Fullstack React with TypeScript Masterclass