reading-notes

Forms

In HTML, form elements such as ,

Controlled Components

In React, a component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.

<input type=”text” value={this.state.value} onChange={this.handleChange} />

Handling Multiple Inputs

When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.

<textarea name=”essay” value={this.state.essay} onChange={this.handleChange} />

<select name=”flavor” value={this.state.flavor} onChange={this.handleChange}> </select>

File Input Tag

In HTML, an lets the user choose one or more files from their device storage to be uploaded to a server or manipulated by JavaScript via the File API. In React, an is always an uncontrolled component because its value can only be set by a user, and not programmatically.

Handling Multiple Files

If you ever need to access more than one file, use the multiple attribute:

<input type=”file” multiple={true} />

The FileList Object

When working with files, you often need to access the file name, file size, and file type. Here’s an example showing how to extract the file name from a FileList object, which is returned by the HTML file input field.

const file = e.target.files[0]; console.log(file.name);

JavaScript: The Conditional Ternary Operator Explained

The ternary operator is a concise way to write simple if statements in JavaScript. It takes three operands:

condition ? expressionIfTrue : expressionIfFalse

If the condition is true, the first expression is evaluated, and the second expression is evaluated if the condition is false.

For example:

const x = 10; const y = 5;

const isGreater = x > y ? true : false; console.log(isGreater); // true

We can also nest ternary operators:

const num = 8;

const isPositive = num > 0 ? true : num < 0 ? false : ‘zero’; console.log(isPositive); // true

This is equivalent to:

let isPositive; if (num > 0) { isPositive = true; } else if (num < 0) { isPositive = false; } else { isPositive = ‘zero’; }

While the ternary operator can make code more concise, it can also make it less readable. Use it judiciously.

React Bootstrap Forms Overview

React Bootstrap provides a set of form components that are compatible with standard HTML form controls.

The Form component is the top-level component for all forms in React Bootstrap. It provides a few helpful props such as onSubmit and validated.

Other form components include:

React Bootstrap forms can also be extended with additional functionality using react-hook-form, a lightweight library for form validation and management.

Overall, React Bootstrap forms provide a flexible and easy-to-use way to create and manage forms in your React applications.

React Conditional Rendering