New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

babel-plugin-react-auto-binding

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

babel-plugin-react-auto-binding

Babel plugin for React component to take event handler to bind context automatically.

latest
Source
npmnpm
Version
1.0.5
Version published
Maintainers
1
Created
Source

babel-plugin-react-auto-binding

Babel plugin for React component to take event handler to bind context automatically.

Installation

$ npm install babel-plugin-react-auto-binding --save-dev

Motivation

When you are building a React component, you have to be careful about event handler. In component, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

Therefore, you have to bind the event handler in constructor method, like this,

class App extends React.Component{
  constructor(props) {
    super(props)
    this.state = {
      view: false
    }
    this.handleClick = this.handleClick.bind(this) // binding method
  }
  handleClick(e) {
    this.setSate({
      view: true
    })
  }
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click me</button>
        <br />
        {
            (view) && <div>React auto binding succeeded</div>
        }
      </div>
    )
  }
}

It's so troublesome. So, this plugin is born to resolve these thorny problems. With this plugin, you can easily code without caring about context.

Instead,

class App extends React.Component{
  constructor(props) {
    super(props)
    this.state = {
      view: false
    }
    // needn't binding method
  }
  
  handleClick(e) {
    this.setSate({
      view: 'value'
    })
  }
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click me</button>
        <br />
        {
            (view) && <div>React auto binding succeeded</div>
        }
      </div>
    )
  }
}

Usage

Write via babelrc.

// .babelrc
{
  "plugins": [
    "react-auto-binding"
  ]
}

Warning

This plugin check the spuerClass after the extends in classDeclaration to know whether it is React component or not.

Only supported React.Component, React.PureComponent, Component, PureComponent

Do not use other words instead of it, like this,

import {Component as ReactComponent} from "react"

class App extends ReactComponent{
  //...
}

Keywords

babel

FAQs

Package last updated on 07 Feb 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts