Fellow Stranger Fellow Stranger - 2 months ago 12
React JSX Question

Render method aware which event handler/state change invoked it?

I use

onMouseDown
,
onMouseOver
,
onMouseUp
with corresponding methods (which all change state).

When only
onMouseUp
is invoked I want to apply some calculations on all rendered child components.

How can go about to do this?

Answer

I think this does what you're looking for:

const SampleComponent = React.createClass({

    getInitialState() {
        return {
            isMouseDown: false,
            isMouseOver: false,
            isMouseUp: false
        };
    },

    handleEvent( e ) {
        const eventType = e.type;
        this.setState({
            isMouseDown: eventType === 'mousedown',
            isMouseOver: eventType === 'mouseover',
            isMouseUp: eventType === 'mouseup'
        });
    },

    renderContent() {

        if ( this.state.isMouseDown ) {
            return ( <p>Mouse is down</p> );
        } else if ( this.state.isMouseOver ) {
            return ( <p>Mouse is over</p> );
        } else if ( this.state.isMouseUp ) {
            return ( <p>Mouse is up</p> );
        }
        return ( <p>default content</p> );
    },

    render() {

        return (
            <div
                onMouseDown={ this.handleEvent }
                onMouseOver={ this.handleEvent }
                onMouseUp={ this.handleEvent }
            >
                { this.renderContent() }
            </div>
        );
    }

});

module.exports = SampleComponent;
Comments