React part 2


React part 2

Lifecycle Methods

React provides special lifecycle methods for class components, which are called when components are mounted, updated or unmounted.

Mounting is the process when a component is rendered on the page. Unmounting is the process when a component is removed from the page.

The componentDidMount method is called when a component is rendered on the page.

componentDidMount is typically used for populating the state inside of a component when it initially mounts to the DOM.

Similarly, the componentWillUnmount() lifecycle method is called right before the component is removed from the DOM. It can be used to free up resources taken by the component.

Another lifecycle method is componentDidUpdate(), which is called when a component is updated in the DOM.

The useEffect Hook

The lifecycle methods we covered are only available for class components. However, React provides a special Hook called useEffect to make lifecycle methods available in functional components. It combines the componentDidMount, componentDidUpdate, and componentWillUnmount methods into one.

Event Handling

Handling events in React is very similar to handling events in the DOM.

The only difference is that event names use camelCase syntax and the event handler needs to be passed in curly braces.

For example, to handle the click event on a button:

<button onClick={handleClick}>
  My Button
</button>

Clicking the button will call the handleClick function of the component.

Handling User Input

One of the common ways that users interact with web pages is through text fields.

We can handle user input in React using the onChange event of the text field. When the value of the text field changes, the event handler is called, updating the value of the field in the component’s state.

This way you always have the actual value of the text field in the state.

Forms

Text fields are usually part of a form.

Similar to the previous example, React form elements keep their state and update it based on user input.

This way you always have the data of your form at your disposal in the state.

To demonstrate this, we will create a form, that will add numbers every time the form is submitted and display the sum.

Our form contains an input field and a submit button:

function AddForm() {
  const [sum, setSum] = useState(0);
  const [num, setNum] = useState(0);

  function handleChange(e) {
    setNum(e.target.value);
  }

  function handleSubmit(e) {
    setSum(sum + Number(num));
    e.preventDefault();
  }

  return <form onSubmit={handleSubmit}>
  <input type="number" value={num} onChange={handleChange} />
  <input type="submit" value="Add" />
  <p> Sum is {sum} </p>
  </form>;
}

Lists

Web apps commonly contain repeating elements, such as lists or sections, where the same DOM element is repeated with a different data set.

Consider an array of strings:

const arr = ["A", "B", "C"];

We need to render a list <li> element for each item in the array. We can define a MyList component and pass it the array as a prop using a custom data attribute:

<MyList data={arr} />

Now, when the array is accessible via props, we can write the component logic:

function MyList(props) {
  const arr = props.data;
  const listItems = arr.map((val) =>
    <li>{val}</li>
  );
  return <ul>{listItems}</ul>;
}

We take the input array from the incoming props, loop through the array using the JavaScript map function and return a <li> element for each item. The resulted array is stored in the listItems variable. Then, the component returns the listItems array inside a <ul> tag.

Keys

Each element in a list must have a key attribute. Keys act as a unique identity, identifying each element. Usually, these are IDs from your data, or can be auto-generated indexes.

For example:

const listItems = arr.map((val, index) =>
  <li key={index}>{val}</li>
);

Keys are important, because they uniquely identify elements, helping React understand which items have changed, are added, or are removed.