Search code examples
javascriptreactjsmeteorreact-reduxonsen-ui

How do I modify the default name of react-redux connect function?


I'm using onsen-ui to style a meteor app with React for the frontend. As I understand it, onsen-ui manages navigation by pushing pages to a stack, where each page has a unique identifier.

Here is how my pages are loaded in App.js

loadPage = (page) => {
    const currentPage = this.navigator.pages.slice(-1)[0]

    if(currentPage.key != page.name){
        this.navigator.pushPage(
            {
                component: page,
                props: { key: page.name }
            },
            {
                animation: 'fade',
                animationOptions: {duration: 0.3, timing: 'ease-in'}
            },
        );
    }
}

So far everything works fine. But I have now included redux in my project, so I have some components which are connected to the store by react-redux's connect() function.

The problem is that for every component that connect wraps, the name property becomes Connect, so onsen-ui is having to deal with multiple pages with the same name in its stack.

As an example, let's say I have a component defined below

const ComponentName = props => {
    return (
        <p>Test component</p>
    )
}

export default connect()(ComponentName)

ordinarily, ComponentName.name returns ComponentName but once its wrapped with connect, ComponentName.name returns Connect

Is it at all possible to modify the name value for the wrapped component?

Every suggestion is welcome.

Edit: Following Vlatko's lead, this is how I eventually solved the problem.

export const getPageKey = (page) => {
    // returns a page key
    let key;
    if (page.name === 'Connect') {
        key = page.displayName
        // key = page.WrappedComponent.name
        // react-redux connect returns a name Connect
        // .displayName returns a name of form Connect(ComponentName)
        return key.replace('(', '').replace(')', '')
    }
    else {
        key = page.name
        return key
    }
}

So for every component I just get the key with getPageKey(ComponentName)

Edit 2. This approach doesn't work in production.

In production mode, I get single letters for page.displayName and those letters are hardly unique, which means I'm back where I started.

I need to find another approach. I'll update whatever I find.


Solution

  • This is happening because you are exporting your component through a higher order function (Connect), which is basically a closure in JavaScript.

    The name of the HOC that you are using is Connect, and this is returned.

    However, it is possible to get the name of the component passed into the connect HOC.

    ComponentName.name // Connect
    ComponentName.displayName // Connect(ComponentName)
    ComponentName.WrappedComponent.name // ComponentName