John Doe John Doe - 3 months ago 42
React JSX Question

React/prefer-stateless-function vs class decorators?

So, I am setting up a brand new React project, and have updated all my deps to the latest versions.

This caused some eslint breakages in the project, so I'm going through and correcting these.

I seem to have come across conflicting rules. React/prefer-stateless-function tries to tell me to write my component as a pure function, but if I do that, I can no longer use decorators to connect my component to my Redux store.

How are people getting around this? The component in question is a "dumb" component (eg only props, no state), so honestly it should be written as a pure function, but then I lose the ability to connect it to my store via

@asyncConnect
and
@connect
.

Class component with decorators:

@connect(
state => ({ // eslint-disable-line
user: state.publicData.user.data,
error: state.publicData.user.error,
loading: state.publicData.user.loading,
}),
{ initializeWithKey })
export default class UserProfile extends Component {
...stuff
}


Pure function component:

// How can I use decorators?
export default function UserProfile(props) {
...stuff
}


Case of two decorators combined:

@asyncConnect([{
deferred: true,
promise: ({ params, store: { dispatch, getState } }) => {
if (!isLoaded(getState())) {
return dispatch(loadUser(params.userID))
}
},
}])
@connect(
state => ({ // eslint-disable-line
user: state.publicData.user.data,
error: state.publicData.user.error,
loading: state.publicData.user.loading,
}),
{ initializeWithKey })
export default class UserProfile extends Component {
...stuff
}

Answer

Redux doesn't need decorators to work, connect is really just a function. You can use it like this:

export default connect(mapStateToProps)(props => <div />)
Comments