Introduction
Introduction of the HTML input box with Transcrypt.
We'll cover the following
Introduction
One of the most fundamental elements used in most web applications is the text box, or more specifically, an HTML input element. By default, the input element allows the user to enter any text value. By specifying the element’s type attribute, we can also get it to be a checkbox or render specifically formatted data like passwords or dates. Let’s look at a basic text input for now and see how we work with it in React.
Reactive input
Remember that React re-renders the page or view whenever there is a change in state. This state change could be triggered by internal events of the application itself, such as data arriving from a network call. It could also be the result of an action by the user. This includes typing a new character into a text box, where the value (or state) of the input element changes every time a character is entered. To make sure that React stays in sync with what the user is doing, we need to make sure we capture and respond to the user by updating the contents of a text box.
Setting up a reactive input
We accomplish that by doing the following:
- Create a state variable in our code to hold the current contents or value of an input box.
- Set the value attribute of that input box to that variable.
- Add an
onChange
event handler to the input box that updates the state variable anytime the user changes the contents of the input box in the UI.
With those steps in place, anytime the value of the React state variable is updated, whether by the user or by our program, React will update the UI to reflect the current state.
Get hands-on with 1400+ tech skills courses.