Skip to content

Instantly share code, notes, and snippets.

@hamlim
Created May 29, 2017 21:45
Show Gist options
  • Save hamlim/d87d8080817135c03390078c99b0239e to your computer and use it in GitHub Desktop.
Save hamlim/d87d8080817135c03390078c99b0239e to your computer and use it in GitHub Desktop.
React-Redux without Context.

What?

React-Redux is a popular redux binding for Reactjs. However it relies on Context within react which is really poorly documented, and isn't well explained that much. It works, and the authors have said they plan on keeping it working even if the context API in React is removed. However I decided on a whim to try and replicate the same functionality without using Context.

Ok cool but why?

Mostly why not.

Is this Production Ready?

Ha! no. This barely even works in an experimental sense let alone on a production level. Just use React-Redux if you want to use an API like that.

I know how to make this better!

Awesome, fork this gist or whatever and share the result because I would love to know how to make this better!

import React, { Component } from 'react';
import { render } from 'react-dom';
const connect = (
mapStateToProps,
mapDispatchToProps = {},
) => WrappedComponent => {
return class ConnectedComponent extends Component {
render() {
return (
<WrappedComponent
{...this.props}
{...mapStateToProps(this.props.store)}
{...mapDispatchToProps}
/>
);
}
};
};
class Provider extends Component {
constructor(props) {
super(props);
this.state = props.store;
}
iterateChildren = children =>
React.Children.map(this.props.children, child => {
return React.cloneElement(
child,
{
...child.props,
store: this.state,
},
this.iterateChildren(child.props.children)
);
});
render() {
return <div>{this.iterateChildren(this.props.children)}</div>;
}
}
const WillBeContainer = props => (
<div>
{props.testing
? <h1 style={{ color: props.color }}>pass</h1>
: <h2>fail</h2>}
</div>
);
const ContainerComp = connect(store => ({ testing: store.testing }))(
WillBeContainer,
);
render(
<Provider store={{ testing: true }}>
<ContainerComp color="red" />
</Provider>,
document.getElementById('root'),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment