Search code examples
reactjsimportreact-reduxexport

Importing a React connect component


Ok, so I have a react-redux component exported like this...

export default {
component: connect(mapStateToProps)(Sites),
loadData

}

Im trying to import this like so...

import Sites from '../views/site/sitesView';

const Home = () =>
AccountService.authenticated() ? (
    <Sites/>
) : (....

I keep getting the following error...

Uncaught Error: Objects are not valid as a React child (found: object with keys {Sites}). If you meant to render a collection of children, use an array instead.

What would be the correct way to import this?

I have tried...

import { Sites } from '../views/site/sitesView';

Thanks.

full code...

    function loadData(store) {
const state = store.getState();
const companyId = state.accountReducer.userinfo.companyId;

return store.dispatch({
    type: siteActions.SITES_COMPANY_REQUESTED,
    payload: {
        companyId: companyId,
        page: 1,
        items: 50
    }
});

}

function mapStateToProps(state, ownProps) {
return {
    loading: state.siteReducer.isRequesting,
    companyId: state.accountReducer.userinfo.companyId,
    sites: state.siteReducer.sites,
    countries: state.countryReducer.countries
}

}

export default { component: connect(mapStateToProps)(Sites), loadData }


Solution

  • What you're exporting by default is an object with multiple properties, not the component alone.

    import Sites from '../views/site/sitesView';
    

    When you do this, the variable Sites is assigned the whole object you exported, which includes a property with the component and another with the loadData method. This means that, even if you gave it the same name, this imported Sites is not actually the React component, and that's why React doesn't recognize as such.

    The real component is inside of your imported object's component property, so in order to render it you'll need to reference it directly:

    <Site.component />
    

    If you'd rather avoid this explicit reference, you should consider changing the way you're exporting the data. I'll suggest exporting the component only by default, and add individual exports to any other values or functions you usually won't need, like this:

    export function loadData () { ... }
    
    export default connect(mapStateToProps)(Sites)
    

    With this alternative, you could import both things like this:

    import Sites, { loadData }  from '../views/site/sitesView';
    

    Sites would now contain only the component, so you could use <Sites /> directly in your render method. If you need to use any method or other exported values, you can do so with a syntax similar to the above.