Event handlers in React

Simple event handlers in React

import React from "react";

class SearchBar extends React.Component {
  onInputChange(event) {
    console.log(event.target.value);
  }

  render() {
    return (
      <div className="ui segment">
        <form className="ui form">
          <div className="field">
            <label htmlFor="searchfield">Search term</label>
            <input
              name="searchfield"
              type="text"
              placeholder="fill in your searchterm"
              onChange={
                this.onInputChange
                // DO NOT put () on functions when passing them to an event handler like onChange, that would call the function everytime its rendered instead of everytime there is a change.
              }
            />
          </div>
        </form>
      </div>
    );
  }
}

export default SearchBar;


it makes sense to refactor the code above and make use of a single line arrow function instead when the onChange event triggers a very simple single line functionality, as below:

import React from "react";

class SearchBar extends React.Component {
  render() {
    return (
      <div className="ui segment">
        <form className="ui form">
          <div className="field">
            <label htmlFor="searchfield">Search term</label>
            <input
              name="searchfield"
              type="text"
              placeholder="fill in your searchterm"
              onChange={(e) => console.log(e.target.value)}
            />
          </div>
        </form>
      </div>
    );
  }
}

export default SearchBar;

However, we now have a UNCONTROLLED component where the value is stored in the HTML. This is not OK! We need to refactor it into a controlled component instead

  1. user types input
  2. callback gets invoked
  3. we call setstate with the new value
  4. component rerenders
  5. input is told what its value is

// controlled vs uncontrolled
in order to make sure we dont have to reach into the dom to get access to the current value of a input form we use the state object and store the information in there and instead update the dom to get the value from the state object!


import React from "react";


class SearchBar extends React.Component {
  state = { term: "" };

  render() {
    return (
      <div className="ui segment">
        <form className="ui form">
          <div className="field">
            <label htmlFor="searchfield">Search term</label>
            <input
              name="searchfield"
              type="text"
              placeholder="fill in your searchterm"
              value={this.state.term}
              onChange={
                (e) => this.setState({ term: e.target.value })
              }
            />
          </div>
        </form>
      </div>
    );
  }
}

export default SearchBar;

Another real world use case scenario



import React from 'react';

class Validator extends React.Component {
    // State is being initialized in a slightly different way than is shown
    // in the previous videos. You can ignore this different syntax for now.
    constructor(props) {
        super(props);
        this.state = { password: '' };
    }
    
    render() {
        return (
            <div className="ui segment">
                <form className="ui form">
                    <div className="field">
                        <label>Enter Password</label>
                        <input 
                            type="password"
                            value={this.state.password}
                            onChange={(e) => this.setState({ password: e.target.value })}

                        />
                    </div>
                    {this.state.password.length < 4 ? 'Password must be at least 4 characters' : ''}
                </form>
            </div>
        );
    }
}

export default Validator;

Add your comment