I want to write a simple mixin for a tooltip. I already know how to bind my mixin to DOM events:
componentDidMount: function() { var el = this.getDOMNode(); el.addEventListener('mouseenter', this.mouseenter, false); el.addEventListener('mouseleave', this.mouseleave, false); },
…but I’d like to bind to the React events instead, to take advantage of its consistent event system. How do I do it?
Advertisement
Answer
I think you probably want to do this in the render
method of the mixing component, by passing in the mixin’s mouseenter
and mouseleave
handlers as props. I think one option might look like this:
var MouseMixin = { getMouseProps: function() { return { onMouseEnter: this.mouseenter, onMouseLeave: this.mouseleave } }, mouseenter: function() { console.warn('mouseenter', arguments) }, mouseleave: function() { console.warn('mouseleave', arguments) } };
Then, in addition to mixing this in, you’d need to apply the behavior. In JSX in React 0.12, you can use the ...
spread operator to help with this:
var Example = React.createClass({ mixins: [MouseMixin], render: function() { return ( <div { ...this.getMouseProps() }> Hello world </div> ) } });