DEV Community

Cover image for React 101 - part 4: Events and Forms
Eric The Coder
Eric The Coder

Posted on

React 101 - part 4: Events and Forms

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.

Events

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 this keyword always represent the object that defined the arrow function.

Here a full example of a classic Counter Component

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'))

Enter fullscreen mode Exit fullscreen mode

Counter Component

Forms

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:

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'))

Enter fullscreen mode Exit fullscreen mode

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 e 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.

Textarea

the same exact concept apply to textarea. In HTML textarea have no value attribute. In HTML you insert the value between the tag element

<textarea>This is the text area content</textarea>
Enter fullscreen mode Exit fullscreen mode

In React to set the value of a textarea we use the value attribute same as a regular input

<textarea onChange={(e) => this.handleChange(e)} value={this.state.note} type="text" id="note" name="note" /></textarea>
Enter fullscreen mode Exit fullscreen mode

Select

For a select field it's exacly the same. We will not use the selected attribute. In React we will use a value attribute.

<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>
Enter fullscreen mode Exit fullscreen mode

Multiple Select

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

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>
  }
}
Enter fullscreen mode Exit fullscreen mode

Checkbox

For checkbox React will use the checked boolean attribute

<input type="checkbox" checked={this.state.checked} onChange={e => this.handleChange(e)} />
Enter fullscreen mode Exit fullscreen mode
handleChange(e) {
  this.setState({checked: e.target.checked})
}
Enter fullscreen mode Exit fullscreen mode

React input vs classic HTML input

When an input field is use inside a React component. This input field do not behave like a regular HTML field anymore

<input onChange={(e) => this.handleChange(e)} value={this.state.name} type="text" id="Name" name="name" />
Enter fullscreen mode Exit fullscreen mode

If you want that input field to behave like a classic HTML input. You need to remove the value attribute.

<input type="text" id="Name" name="name" />
Enter fullscreen mode Exit fullscreen mode

If you want to set a default value for that input field. Since you cannot set value, you can use defaultValue

<input type="text" defaultValue="Mike" id="Name" name="name" />
Enter fullscreen mode Exit fullscreen mode

Submit Form

To submit a form we will create a form tag and call a onSubmit event

<form onSubmit={(e) => this.handleSubmit(e)}>
  ...
</form>
Enter fullscreen mode Exit fullscreen mode

The handleSubmit use e.preventDefault to prevent the form to send a post request and refresh the browser

handleSubmit(e) {
    e.preventDefault();
    console.log(this.state)
}
Enter fullscreen mode Exit fullscreen mode

Here is a complete form submit example


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'))

Enter fullscreen mode Exit fullscreen mode

Conclusion

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

Discussion (0)