deadcoder0904
deadcoder0904

Reputation: 8683

Wrapping Provider in same component throws Element type is invalid: expected a string (for built-in components) or a class/function but got: object

I wrote a simple counter example in both Mobx & Redux & it works

Full demo is available https://codesandbox.io/s/nw303w6jxl

But if I remove Provider from ./src/index.js

const App = () => (
  <div className="container">
    <Mobx />
    <hr />
    <Provider store={store}>
      <Redux />
    </Provider>
  </div>
);

& put it in ./src/redux.js while default exporting it throws an error

export default (
  <Provider store={store}>
    <ConnectReduxApp />
  </Provider>
);

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

Its working but I don't know why its happening? I checked the typeof the default exported function from ./src/redux.js ,i.e,

console.log(
    typeof(
       <Provider store={store}>
         <ConnectReduxApp />
       </Provider>
    )
);

& its an object but what if I want to use Redux only in a part of my React Application. Lets say a form. Then by this way it will throw an error. Any help is appreciated.

Upvotes: 1

Views: 396

Answers (1)

rowinbot
rowinbot

Reputation: 632

This is happening because you're exporting not a function returning JSX nor a class with a render method that returns JSX, you're exporting JSX itself.

Either render it like {reduxImported}:

import reduxImported from './src/redux.js'
...
render() {
  <Container>
    {reduxImported}
    <MobX />
  </Container>
}

Or change your export to:

export default () => (
  <Provider store={store}>
    <ConnectReduxApp />
  </Provider>
)

Upvotes: 4

Related Questions