Skip to content

Instantly share code, notes, and snippets.

@kishanio
Last active May 4, 2017 06:43
Show Gist options
  • Save kishanio/9aad602bdf8a0baa1b174d37dd2a1e43 to your computer and use it in GitHub Desktop.
Save kishanio/9aad602bdf8a0baa1b174d37dd2a1e43 to your computer and use it in GitHub Desktop.
ReactRedux : Generating Container Components
// Dependency : https://github.com/reactjs/react-redux
// Writing a container to pass todos & onTodoClick as Props to child.
// We needed this container in order to subscribe and unsubscribe to state.
class VisibleTodoList extends Component {
componentDidMount() {
const { store } = this.context;
this.unsubscribe = store.subscribe( () => this.forceUpdate() );
}
componentWillUnmont() {
this.unsubscribe();
}
render() {
const props = this.props;
const { store } = this.context;
const state = store.getState();
return (
<TodoList
todos={getVisibileTodos( state.todos, state.visibilityFilter)}
onTodoClick={ id => store.dispatch({ type: 'TOGGLE_TODO', id }) }
/>
);
}
}
VisibleTodoList.contextTypes = {
store: React.PropTypes.object
};
// Above container can be rewritten using connect.
// both mapping updates everytime state changes
const mapStateToProps = (state) => {
return {
todos: getVisibileTodos( state.todos, state.visibilityFilter)
};
};
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => dispatch({ type: 'TOGGLE_TODO', id })
};
}
// we can generate container by using connect function provided by redux.
const { connect } = ReactRedux;
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList); // Connect is a curried function and last argument is Presentation component
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment