ReadingNotes

React and Forms

Forms

JavaScript: The Conditional (Ternary) Operator

Forms Questions

  1. A ‘controlled component’ in React refers to an input form element whose value is controlled by React through its state. This means that the value of the form element is kept in the component’s state and is updated whenever the user types in the input field.
  2. In most cases, it’s better to update the state with the user’s responses as soon as they enter them, rather than waiting until they submit the form. There are several reasons for this:

Real-time feedback: Updating the state with the user’s responses as they enter them allows for real-time feedback and validation. This means that the user can see the results of their input immediately, rather than having to wait until they submit the form to see if there are any errors.

Improved user experience: By providing real-time feedback, users are more likely to have a positive experience with the form. They can see what they are doing correctly and what they need to fix in real-time, which can be very helpful.

Easier to manage: Storing the user’s responses in state as they enter them can also make it easier to manage the data. When the user submits the form, you can simply grab the data from state and process it, rather than having to collect all of the data from the form fields.

That being said, there may be some cases where you want to wait until the user submits the form to update the state. For example, if you have a multi-page form, it may be better to update the state only after the user has completed all the pages and submitted the form. However, in most cases, updating the state with the user’s responses as they enter them is the better approach.

  1. To target what the user is entering if we have an event handler on an input field, we can use the event.target.value property to get the current value of the input field.

ternary

  1. The ternary operator is used as a shorthand for an if…else statement when there are only two possible outcomes.
  2. console.log(x === y ? true : false);