Reusing Components
Sometimes it makes sense to reuse components for different purposes. Since mapStateToProps
defines the properties passed in, components can be wrapped
more than once. The one rule is the wraps
must conform to the components API. Here is an example where one button component can "follow" different things.
Let's say a user can follow other "users" or "groups." Our component looks like this:
// FollowButton.js
export function FollowButton({actions}) {
return (
<div className="fancy-follow-button" onClick={actions.follow}>
Follow
</div>
);
}
Now let's show the implementations for reusing this component.
// FollowUser.js
import FollowButton from './FollowButton';
import { wrap } from 'coflux';
export default wrap(FollowButton, {
// used in the action
mapStateToProps() {
return {
userId: users[0].id,
isFollowing: users[0].isFollowing,
};
},
actions: {
// Component expects actions.follow
follow(state, next) {
// optimistic update
next({isFollowing: true});
ajaxSetFollowUser(state.userId).catch(() => {
next({isFollowing: false});
});
},
},
});
And now FollowingGroups:
// FollowGroup.js
import FollowButton from './FollowButton';
import { wrap } from 'coflux';
export default wrap(FollowButton, {
// used in the action
mapStateToProps() {
return {
groupId: groups[0].id,
isFollowing: groups[0].isFollowing,
};
},
actions: {
// Component expects actions.follow
follow(state, next) {
// optimistic update
next({isFollowing: true});
ajaxSetFollowGroup(state.groupId).catch(() => {
next({isFollowing: false});
});
},
},
});
Both wraps
define their API's to do slightly different things. As long as they conform to the components spec, re-usability is a breeze!