react-redux icon indicating copy to clipboard operation
react-redux copied to clipboard

Getting Invariant Violation when using redux-react with Typescript/TSX

Open psbanka opened this issue 11 years ago • 4 comments

Now that Typescript supports JSX (with TSX), I'm excited to use React and Redux with it! However, I seem to be getting an issue when I try to wrap a React class with Provider. The code is as follows:

Invariant Violation: onlyChild must be passed a children with exactly one child.

The files I'm using are in This gist

As I dug into the redux-react code, the error is being generated from this stanza:

  Provider.prototype.render = function render() {
    var children = this.props.children;

    return _react.Children.only(children);
  };

And it turned out that this.props.children was a function which returned a React element rather than a React element itself? I don't know how this could be occurring. Any suggestions would be appreciated!

psbanka avatar Oct 18 '15 17:10 psbanka

The code you're running is for Redux React 3.x. The version you're using is 4.x.

4.x no longer allows function-as-a-child for <Provider> because the only reason we had it is for React 0.13 compat, and now we require React 0.14.

https://github.com/rackt/react-redux/releases/tag/v4.0.0

You need to change

React.render(
    <Provider store={store}>
        {() => <Main />}
    </Provider>, document.body);

to

ReactDOM.render(
    <Provider store={store}>
        <Main />
    </Provider>, document.body);

gaearon avatar Oct 19 '15 12:10 gaearon

Thanks for the quick answer!

psbanka avatar Oct 20 '15 16:10 psbanka

I'm facing the same issue. Can't solve it!!

paramsingh88 avatar Jun 17 '16 10:06 paramsingh88

@paramsingh88 can you paste your code? I was getting this same error message but that's because I put a comment between the tags.

FROM

render( // React render
  <Provider store={store}> {/* Provider component from react-redux */}
    <Router history={browserHistory} routes={routes} />
  </Provider>, 
  document.getElementById('app') // root element of react app
);

TO

render( // React render
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>, 
  document.getElementById('app') // root element of react app
);

The second code block works fine for me after I removed this comment {/* Provider component from react-redux */}

dannypule avatar Oct 09 '16 20:10 dannypule