Vlady Veselinov
Vlady Veselinov

Reputation: 5401

Wrapping a high order component(HOC) around a React component in JSX

I'm using the JSX style of writing React and I'm trying to access the functionality of this onClickOutside wrapper to find out when the user clicks away. Here's the usage in its README:

// How to install: npm install react-onclickoutside --save
// load the High Order Component:
var onClickOutside = require('react-onclickoutside');

// create a new component, wrapped by this onclickoutside HOC:
var MyComponent = onClickOutside(React.createClass({
  ...,
  handleClickOutside: function(evt) {
    // ...handling code goes here...
  },
  ...
}));

I tried to access the "click outside" functionality it in this case (in JSX), but it didn't work.

import React from 'react';
import OnClickOutside from 'react-onclickoutside';

export default class Menu extends React.Component {

    constructor(props){
        super(props);
    }


    render() {

        return (
            <OnClickOutside>
                <ul>
                    <li>Test 1</li> 
                    <li>Test 2</li> 
                    <li>Test 3</li> 
                </ul>
            </OnClickOutside>
        );
    }


    handleClickOutside(event) {
        console.log('Clicked outside.');
    }
}

Upvotes: 0

Views: 1564

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67296

I think you are confusing a Higher-Order Component (HOC) and a Container Component in this case. A HOC takes a Component (in your case Menu) and then returns a Component (composed with the HOC functionality). While a Container Component renders its children.

As the example shows, the onOutsideClick Component is a HOC. This should work for your example:

import React from 'react';
import OnClickOutside from 'react-onclickoutside';

export class Menu extends React.Component {

    constructor(props){
        super(props);
    }


    render() {

        return (      
                <ul>
                    <li>Test 1</li> 
                    <li>Test 2</li> 
                    <li>Test 3</li> 
                </ul>
        );
    }


    handleClickOutside(event) {
        console.log('Clicked outside.');
    }
}

export default OnOutsideClick(Menu);

Upvotes: 3

Related Questions