Importing generic handlers

Any React application is likely going to share the same event handling logic for different components. For example, in response to a button click, the component should sort a list of items. It's these types of generic behaviors that belong in their own modules so that several components can share them. Let's implement a component that uses a generic event handler function:

import React, { Component } from 'react';

// Import the generic event handler that
// manipulates the state of a component.
import reverse from './reverse';

export default class MyList extends Component {
state = {
items: ['Angular', 'Ember', 'React']
};

// Makes the generic function specific
// to this component by calling "bind(this)".
onReverseClick = reverse.bind(this);

render() {
const { state: { items }, onReverseClick } = this;

return (
<section>
{/* Now we can attach the "onReverseClick" handler
to the button, and the generic function will
work with this component's state. */}
<button onClick={onReverseClick}>Reverse</button>
<ul>{items.map((v, i) => <li key={i}>{v}</li>)}</ul>
</section>
);
}
}

Let's walk through what's going on here, starting with the imports. You're importing a function called reverse(). This is the generic event handler function that you're using with your <button> element. When it's clicked, the list should reverse its order.

The onReverseClick method actually calls the generic reverse() function. It is created using bind() to bind the context of the generic function to this component instance.

Finally, looking at the JSX markup, you can see that the onReverseClick() function is used as the handler for the button click.

So how does this work, exactly? You have a generic function that somehow changes the state of this component because you bound context to it? Well, pretty much, yes, that's it. Let's look at the generic function implementation now:

// Exports a generic function that changes the 
// state of a component, causing it to re-render 
// itself.
export default function reverse() { 
  this.setState(this.state.items.reverse()); 
} 

This function depends on a this.state property and an items array within the state. The key is that the state is generic; an application could have many components with an items array in its state.

Here's what our rendered list looks like:

As expected, clicking the button causes the list to sort, using your generic reverse() event handler:

Next, you'll learn how to bind the context and the argument values of event handler functions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.115.120