Controlled & Uncontrolled Inputs In React

Controlled & Uncontrolled Inputs In React

Table of contents

Intro

  1. In React, the label tag is used to associate a label with an input element using the htmlFor attribute. This helps improve accessibility by providing a way for users to easily associate a label with its corresponding input element.

  2. When using a label with an input element in React, you can use either the "controlled" or "uncontrolled" approach to handle form input.

  3. In the "controlled" approach, you bind the value of the input element to a state variable using the onChange event handler. In this case, you would use both an opening and closing tag for the input element, like so:

<label htmlFor="myInput">My input:</label>
<input id="myInput" value={inputValue} onChange={handleInputChange} />
  1. In the "uncontrolled" approach, you don't bind the value of the input element to a state variable. In this case, you would only use a closing tag for the input element, like so:
<label htmlFor="myInput">My input:</label>
<input id="myInput" />
  1. So whether or not you use an opening tag for the input element depends on whether you are using the "controlled" or "uncontrolled" approach to handle form input in React.