2 min read

Setting up an es6 component in react is pretty simple. Today I wanted to show quickly how to use bind() to set up an onchange or any other global event handler to run a react function.

There are a lot of ways to do this, but this is my personal favorite usage.

we start off by our base react component:

import React, { Component } from 'react';

export class myComponent extends Component {
    constructor(props){
        super(props);
        this.state = {
            exampleState: "Initial State"
        }
    }

    render(){
        return(
            <div>
                <h1>Make a Component!!</h1>
                <p>{this.state.exampleState}</p>
            </div>
        )
    }
}

Next up we throw a nice easy dropdown component into our page:

<select onChange={this.selectKey.bind(this)}>
  <option key={1} value='value 1'>Value 1</option>
  <option key={2} value='value 2'>Value 2</option>
  <option key={3} value='value 2'>Value 3</option>
</select>

Notice what we did here, we have onChange={this.selectKey.bind(this)} to create an identifier of a function. Because this, is always linked to the function that is calling this in order to escape the function directly to the class creator we use bind(this) to bind it to extends Component instead.

This allows us to use a function in the creation of the element. Next we create a simple function to update our exampleState:

selectKey(event) {
  this.setState({exampleState})
}

By doing this we have used setState to set our exampleState to whatever the value is of the select box.

The final result of our code is:

import React, { Component } from 'react';

export class myComponent extends Component {
  constructor(props){
    super(props);
      this.state = {
        exampleState: "Initial State"
      }
  }

  selectKey(event) {
    this.setState({exampleState})
  }

  render(){
      return(
        <div>
          <h1>Simple Select Box!!</h1>
          <select onChange={this.selectKey.bind(this)}>
            <option key={1} value='value 1'>Value 1</option>
            <option key={2} value='value 2'>Value 2</option>
            <option key={3} value='value 2'>Value 3</option>
          </select>
          <p>{this.state.exampleState}</p>
        </div>
      )
  }
}

Using these fundamentals you can pretty much anything you want with global handlers at this point. Enjoy!

standard horrible howto disclaimer: I'm not making these for any professional reason, but more as a point of reference for design, if you see any discrepancies, or more efficient ways, drop a comment below!

Sam Clark

Sam Clark

Read more posts by this author.