I am starting to develop a web application using React JS. I bought a theme from theme forest. In the theme, they are using compose like this in the component.
...Other code here Login.propTypes = { classes: PropTypes.shape({}).isRequired, width: PropTypes.string.isRequired }; export default compose(withWidth(), withStyles(themeStyles, { withTheme: true }))(Login);
As you can see their code is using the compose at the end when exporting the Component. I cannot modify their built-structure. What I like to do now is I like to use connect feature of the react as well.
Normally connect is used in the place of compose. Now, if I want to use connect to work with the state of the application, how can I use it together with compose ?
Overview The connect() function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.
Compose is used when you want to pass multiple store enhancers to the store. Store enhancers are higher order functions that add some extra functionality to the store. The only store enhancer which is supplied with Redux by default is applyMiddleware however many other are available.
Since you can have only one default export, you'd have to use named export in this case or split up those two components in two files.
The React Redux connect() API is used for creating container elements that are connected to the Redux store. The Redux store is derived from the topmost ancestor of the component using React Context. If you are only creating a presentational component, you have no need for connect() .
const enhance = compose( withRouter, withStyles(styles, 'some style'), connect(mapStateToProps, mapDispatchToProps), .... export default enhance(MyComponent);
import {bindActionCreators} from 'redux'; import compose from 'recompose/compose'; import { connect } from 'react-redux'; ...Other code here function mapStateToProps(state) { return { //return state } } function mapDispatchToProps(){ return bindActionCreators({ //actions }, dispatch); } Login.propTypes = { classes: PropTypes.shape({}).isRequired, width: PropTypes.string.isRequired }; export default compose(withWidth(), withStyles(styles, {withTheme: true}), connect(mapStateToProps, mapDispatchToProps))(Login);
I hope this solves your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With