How to Bind this in React Without a Constructor | Tiffany R. White Blog

How to Bind this in React Without a Constructor

Reading time: 2 mins

this in React is a reference to the current component. Usually this in React is bound to its built-in methods so that when you want to update state or use an event handler on a form, you could do something like this:

<input type="text" ref={this.someInput} required placeholder="This is a Method" defaultValue={getSomeMethod()}/>

where this.someInput is passing state to whichever React component you are rendering.

Unfortunately, though, React doesn’t auto-bind this to custom methods. This means if I wanted to manipulate the DOM by getting some input, which you can’t do as you can with normal JavaScript, I would create a ref to do whatever DOM tinkering I wanted.

But because React doesn’t auto-bind this, the following code would output undefined when logged:

someInput = React.createRef();
  renderSomeInput (event) {
    event.preventDefault();
    const someFunction = this.someInput.value.value;
    console.log(this);
  }

In order to avoid this, we could use the constructor function in order to initialize or get the state we want:

class SomeCompenent extends React.Component {
  constructor() {
    super();
    this.renderSomeInput.bind(this);
  }
}

While this is a decent way to initialize state, what if you wanted to bind several custom methods in one component? It would get pretty messy…

class SomeCompenent extends React.Component {
  constructor() {
    super();
    this.renderSomeInput.bind(this);
    this.renderSomeInput.bind(this);
    this.renderSomeInput.bind(this);
    this.renderSomeInput.bind(this);
   }
}

You get the idea.

Instead, we can bind this to custom React methods by declaring a method and assigning it to an arrow function:

class SomeCompenent extends React.Component {

  someInput = React.createRef();
    renderSomeInput = (event) =>  {
    event.preventDefault();
    const someFunction = this.someInput.value.value;
    console.log(this);
    }
  }

which will allow us to bind the value of this to the SomeComponent component.



No Ads. No Sponsored Content. Ever.

I've decided that I no longer want to have sponsored posts on this blog. I also, though as tempting as it may sound, don't want ads; even if I got big enough for Carbon ads I don't want them. I want to post free, engaging content for beginning/junior devs. This means that I won't have Setapp posts or affiliates on this blog, though I will keep them on the Uses page. If you enjoy the content, buy me a coffee. Just click the button below.




Webmentions 0

No webmentions were found.