React 101 - part 4: Events and Forms
Tags: javascript, react, beginners, tutorial
Published: 2021-03-10 15:36:10

---
title: React 101 - part 4: Events and Forms
published: true
description: 
tags: javascript, react, beginner, tutorial
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r3ui703pme0meo82pu5o.png
series: React 101
---

After my Javascript series: https://dev.to/rickavmaniac/javascript-my-learning-journey-part-1-what-is-javascript-role-and-use-case-49a3

I am now ready to begin my React learning journey :)

Click follow if you want to miss nothing. I will publish here on Dev.to what I learn from my React course the day before.

Without further ado here is a summary of my notes for day 4.

<h2>Events</h2>
Just like HTML, React can perform actions based on user events. React has the same events as HTML: click, change, mouseover etc.

To create a event listener we use this syntax:
OnClick={() => myFunction()}

The onClick is the event and the callback is the function to execute when the event occur. 

We use an arrow function because with arrow function the <i>this</i> keyword always represent the object that defined the arrow function.

Here a full example of a classic Counter Component
```jsx
class Counter extends React.Component {
  constructor(props) {
    super(props)
    this.state = {count: 0}
  }
  increment() {
    this.setState({count: this.state.count += 1})
  }
  decrement() {
    this.setState({count: this.state.count -= 1})
  }
  render () {
    return <div>
      <h1>Count: {this.state.count} </h1>
      <button onClick={() => this.increment()}>Add</button>
      <button onClick={() => this.decrement()}>Remove</button>
    </div>
  }
}

ReactDOM.render(<Counter />, document.querySelector('#app'))

```
![Counter Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2b4mt8lbvrhtgzeuijqg.png)

<h2>Forms</h2>
Handling forms is about how you handle the data when it changes value or gets submitted.

In React, form data is handled by the components.

When the data is handled by the components, all the data is stored in the component state.

You can control changes by adding event handlers in the onChange attribute. 

Here is a example:
```jsx
class Home extends React.Component {
  constructor(props) {
    super(props)
    this.state = {name: ''}
  }
  handleChange(e) {
    this.setState({name: e.target.value})
  }
  render() {
    return <div>
      <label htmlFor="Name">Your name</label>
      <input onChange={(e) => this.handleChange(e)} value={this.state.name} type="text" id="Name" name="name" />
      <p>{this.state.name}</p>
    </div>
  }
}

ReactDOM.render(<Home />, document.querySelector('#app'))

```
In this last example, when you make any change to the input field. React will call the handleChange event. 

The event is call with a <i>e</i> argument. This argument is a reference to the current event. It contain all the current event info. Like the event element.

Noted that we also set the input field value to {this.state.name}. This value will be use when the form will be submit.

<h2>Textarea</h2>
the same exact concept apply to textarea. In HTML textarea have no value attribute. In HTML you insert the value between the tag element
```html
<textarea>This is the text area content</textarea>
```
In React to set the value of a textarea we use the value attribute same as a regular input
```jsx
<textarea onChange={(e) => this.handleChange(e)} value={this.state.note} type="text" id="note" name="note" /></textarea>
```
<h2>Select</h2>
For a select field it's exacly the same. We will not use the selected attribute. In React we will use a value attribute.
```jsx
<select value={this.state.name} onChange={(e) => this.handleChange(e)}>
    <option value="Mike">Mike</option>
    <option value="John">John</option>
    <option value="Peter">Peter</option>
</select>
```
<h2>Multiple Select</h2>
For multiple select it's the same as a select but the return value will be an array.

e.target.value will not work any more. We can use Array.from(e.target.selectedOptions)

Since we only want value from those selectedOptions we will use a map to extract only values: Array.from(e.target.selectedOptions).map(element => element.value)

Here is the full example with a multi select
```jsx
class Home extends React.Component {
  constructor(props) {
    super(props)
    this.state = {name: ''}
  }
  handleChange(e) {
    this.setState({name: Array.from(e.target.selectedOptions).map(element => element.value )})
  }
  render() {
    return <div>
      <label htmlFor="Name">Your name</label>
      <select value={this.state.name} onChange={(e) => this.handleChange(e)} multiple>
        <option value="Mike">Mike</option>
        <option value="John">John</option>
        <option value="Peter">Peter</option>
      </select>
      <p>{this.state.name}</p>
    </div>
  }
}
```

<h2>Checkbox</h2>
For checkbox React will use the checked boolean attribute
```html
<input type="checkbox" checked={this.state.checked} onChange={e => this.handleChange(e)} />
```
```jsx
handleChange(e) {
  this.setState({checked: e.target.checked})
}
```
<h2>React input vs classic HTML input</h2>
When an input field is use inside a React component. This input field do not behave like a regular HTML field anymore
```jsx
<input onChange={(e) => this.handleChange(e)} value={this.state.name} type="text" id="Name" name="name" />
```

If you want that input field to behave like a classic HTML input. You need to remove the value attribute.
```jsx
<input type="text" id="Name" name="name" />
``` 

If you want to set a default value for that input field. Since you cannot set value, you can use defaultValue
```jsx
<input type="text" defaultValue="Mike" id="Name" name="name" />
```
<h2>Submit Form</h2>
To submit a form we will create a form tag and call a onSubmit event
```jsx
<form onSubmit={(e) => this.handleSubmit(e)}>
  ...
</form>
```
The handleSubmit use e.preventDefault to prevent the form to send a post request and refresh the browser
```jsx
handleSubmit(e) {
    e.preventDefault();
    console.log(this.state)
}
```

Here is a complete form submit example
```jsx

class Home extends React.Component {
  constructor(props) {
    super(props)
    this.state = {name: '', email: ''}
  }
   handleChange(e) {
     const name = e.target.name
     this.setState({
       [name]: e.target.value
     })
   }
   handleSubmit(e) {
      e.preventDefault();
      console.log(this.state)
      this.setState({name: '', email: ''})
   }

  render() {
    return <div>
      <form onSubmit={(e) => this.handleSubmit(e)}>
        <input name="name" value={this.state.name} onChange={(e) => this.handleChange(e)} label="Name" />
        <input name="email" value={this.state.email} onChange={(e) => this.handleChange(e)} label="Email" />
        <button type="submit">Submit</button>
      </form>
    </div>
  }
}

ReactDOM.render(<Home />, document.querySelector('#app'))

```

<h2>Conclusion</h2>
That's it for today. tomorrow the journey continue... If you want to be sure to miss nothing click follow me!