Reputation: 12520
I am trying to create a function that dynamically accepts a component for a Provider. I could of course just add the store to the component, but for simplicity's sake I'd like to try to pass it via a function argument.
For example, I'd like to be able to dynamically create this by passing in MyComponent
:
ReactDOM.render(
<Provider store={reduxStore}>
<MyComponent />
</Provider>,
$('.my-component)[0]
)
This, however, no longer works as of React 0.14.
let provideComponent = function(selector, store, componentCallback) {
ReactDOM.render(
<Provider store={store}>
componentCallback()
</Provider>,
$(selector)[0]
)
}
provideComponent('.my-component', reduxStore, function() {
return <MyComponent />
}
# raises error
# Warning: Failed propType: Invalid prop `children` supplied to `Provider`, expected a single ReactElement.
I've also tried adding the store to the component after it is passed in, but this is forbidden. How can I dynamically pass in a smart component to a Redux provider?
Upvotes: 1
Views: 1272
Reputation: 59367
Try this:
let provideComponent = function(selector, store, componentCallback) {
var Component = componentCallback();
ReactDOM.render(
<Provider store={store}>
<Component />
</Provider>,
$(selector)[0]
)
}
provideComponent('.my-component', reduxStore, function() {
return MyComponent;
}
Remember, JSX is case-sensitive. Both upper case and lower case elements get translated to React.createElement
calls. But upper case elements are treated as Components, and thus passed "naked", whereas lower case elements are treated as DOM elements and passed as strings:
<div>
<Component />
</div>
gets translated to:
React.createElement('div', {},
React.createElement(Component, {})
)
Notice <div>
turns into 'div'
(quotes), whereas <Component />
turns into Component
(no quotes).
* EDIT *
If you want your callback to specify props, instead of passing them during the ReactDOM.render()
call, you would do something like this:
let provideComponent = function(selector, store, componentCallback) {
ReactDOM.render(
<Provider store={store}>
{componentCallback()}
</Provider>,
$(selector)[0]
)
}
// Return the actual element, instead of just the type
provideComponent('.my-component', reduxStore, function() {
return <MyComponent prop1="value" prop2="value" />;
}
Upvotes: 4