How to avoid the need for binding in React?

Technology CommunityCategory: ReactHow to avoid the need for binding in React?
VietMX Staff asked 3 years ago

There are several common approaches used to avoid methods binding in React:

  1. Define Your Event Handler as an Inline Arrow Function
class SubmitButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isFormSubmitted: false
    };
  }

  render() {
    return (
      <button onClick={() => {
        this.setState({ isFormSubmitted: true });
      }}>Submit</button>
    )
  }
}
  1. Define Your Event Handler as an Arrow Function Assigned to a Class Field
class SubmitButton extends React.Component {
  state = {
    isFormSubmitted: false
  }

  handleSubmit = () => {
    this.setState({
      isFormSubmitted: true
    });
  }

  render() {
    return (
      <button onClick={this.handleSubmit}>Submit</button>
    )
  }
}
  1. Use a Function Component with Hooks
const SubmitButton = () => {
  const [isFormSubmitted, setIsFormSubmitted] = useState(false);

  return (
    <button onClick={() => {
        setIsFormSubmitted(true);
    }}>Submit</button>
  )
};