Over the past two months, I have been working on an interesting project at my company which is supposed to be a very big one. So at first, as a team leader and core maker, I spent quite a lot of time to find a good starting point, I meant stuff like how to structure the project, which frontend stack to use, how that stack connects to server, how to set up and bring all those things together, etc, to satisfy all the project’s requirements.....
1. React – Structure Container Component In Meteor
M E T E O R ( H T T P S : / / B L O G . D E S I G N V E L O P E R . C O M / C A T E G O R Y / M E T E O R / )
B y K h a n g N g u y e n L e ( h t t p s : // b l o g . d e s i g n v e l o p e r. c o m / a u t h o r / k h a n g n l h / ) o n J u n e 2 1 , 2 0 1 6
2. FYI:
This is one of three topics of our rst Meteor Meetup on June 4th, 2016 (https://blog.designveloper.com/2016/06/14/meteor-ho-chi-minh-meetup-2016-06-04/). The author is Khang Nguyen, a young talent member of
Designveloper. This is an article on his blog, you can read the original article here (http://nlhuykhang.github.io/javascript/framework/2016/04/29/react-structure-container-component-in-meteor.html).
Introduction
Over the past two months, I have been working on an interesting project at my company which is supposed to be a very big one. So at rst, as a team leader and core maker, I spent quite a lot of time to nd a good starting
point, I meant stuff like how to structure the project, which frontend stack to use, how that stack connects to server, how to set up and bring all those things together, etc, to satisfy all the project’s requirements.
Finally, I settled down with Meteor for backend, React for frontend, and Vanilajs ES6 MVC for the app extension (this was the most interesting part of the project. I will talk about it in another blog). At rst things went well and
smooth. Needless to say that React was so amazing that I completely changed my thoughts when programming.
But soon later, since this was the rst time I had really built such a big project with React, things started to get messy. I encountered a problem that every big project coded in React had. Hence, I have this post written to let
you know what problem was and how I attempted to solve it.
Prerequisites
React is introduced to be simple and very easy to learn for beginners. That is de nitely true, but frankly speaking, it takes quite an effort to come up with when you are at beginner level.
Unfortunately, this post is not aimed for beginners because I am writing about experience I learned in a big project, not just the way to use React for Meteor project. So it may require readers to have the following knowledge
to understand what I am going to write:
React container component (https://goo.gl/xxGHnu)
React unidirectional data ow (http://redux.js.org/docs/basics/DataFlow.html)
React Mixins (http://goo.gl/mDj9fO)
React in Meteor 1.2 (https://goo.gl/V5v271)
Ramdajs (http://goo.gl/x2Sblm)
The problem that I encountered
I can summary the problem with only one word, and that is maintainable.
Follow the unidirectional data ow principle, I created a container component for each routes for the problem. This component is in charge of almost every logic stuff for the route it is being used for. E.g. it takes care of
subscribe data/call methods from Meteor server, is a middle man for its children components talking to one another. With all those missions, soon it becomes a very big and fat guy.
The le in which I coded the container component in was about 700 lines when I just nished about half of the work. This was clearly unacceptable. If I had ignored this problem and kept coding to get the job done fast, it
would have been a nightmare for maintainer/debugger.
Knowing that this was my company’s main project, meaning that my colleagues and I would be working on it for years, I stopped coding features and started reviewing the code.
First attempt
I looked at all the container’s functions and realized that they could be categorized into four groups:
Component’s must-have functions: getInitialState, getMeteorData, render, etc…
Handler functions: all event handlers for all container’s children components
Helper functions: functions to help get necessary data for container’s children components based on container props and state. There functions are merely pure functions, they take input and produce output without
touching the container state or talking to Meteor server.
Logic functions: functions to modify the component state, call methods from server. These functions are called by event handlers in response to user actions.
With this model in mind, I decoupled the last three groups’ functions into three separate les and imported them back in the container through mixins.
3. The directory of the container looked like this:
root
| ...
|---...
|---poppi:client-container-example-component
|---client
|---components
|---subcomponent1
| ...
|---subcomponent2
| ...
| ContainerExample.jsx
| ContainerExampleContainer.jsx
| ContainerExampleHandlers.js
| ContainerExampleHelpers.js
| ContainerExampleLogicFuncs.js
| package.js
|---...
And also the code of the container
ContainerExampleContainer = React.createClass({
mixins: [
ReactMeteorData,
ContainerExampleHandlers,
ContainerExampleHelpers,
ContainerExampleLogicFuncs,
],
getInitialState() {
...
},
getMeteorData() {
...
},
render() {
...
},
});
My container looked much better. It became a thinner and more handsome guy. When you need to nd a function, I recommend this decoupling technique for a faster and more semantic solution. However, it would be even
better if I did not face a hurdle
Push it a bit further
Even though I separated all functions into 3 different mixin les, I had not had any idea on where to put each function yet. All the time I had to check those 3 functions to identify the appropriate function places. This was time-
consuming and I needed a more ef cient way. The only way that I thought of at that time was looking at the function calling statement.
After thinking for a while, I fell back to the basic technique widely in js: “namespace”. I grouped all the functions under a namespace obj inside the mixin obj. My three mixin le then became:
4. // ContainerExampleHandlers.js
ContainerExampleHandlers = {
Ha: {
clickHandler() {
this.L.test1();
return;
},
},
};
// ContainerExampleHelpers.js
ContainerExampleHelpers = {
He: {
getData(state) {
return {
state
};
},
}
};
// ContainerExampleLogicFuncs.js
ContainerExampleLogicFuncs = {
L: {
test1(param1) {
const data = this.He.getData(param1);
this.setState({
...data,
});
},
test2(param2) {
Meteor.call('test2', param2);
}
},
};
By just looking at the calling function statement, I knew exactly where these functions came from. This is extremely useful and ef cient when working on a big and complicated project.
But unfortunately I still could not enjoy the fantasy of this technique, because the scope inside all functions was wrong.
So I had to bind their contexts to the right ones.
Ramda to the rescue
The binding process could be done easily by a for-in loop inside the getInitialState function of the container. But it required more than that and I needed a more uni ed, modern, handy and understandable way, also shorter
one to use in this big project. Luckily, the rise of Ramda recently got my attention and turned out to be the best t for my requirements.
Finally I came up with this binding function:
// bindMixinFunctions.js
bindMixinFunctions = R.converge(function(keys, values, ctx) {
const bindValues = R.map((val) => R.bind(val, ctx), values);
return R.zipObj(keys, bindValues);
}, [
R.flip(R.keys),
R.flip(R.values),
R.identity
]);
5. And use it in action:
ContainerExampleContainer = React.createClass({
mixins: [
ReactMeteorData,
ContainerExampleHandlers,
ContainerExampleLogicFuncs,
ContainerExampleHelpers,
],
getInitialState() {
const thisBindMixinFunctions = bindMixinFunctions(this);
this.He = thisBindMixinFunctions(this.He);
this.Ha = thisBindMixinFunctions(this.Ha);
this.L = thisBindMixinFunctions(this.L);
...
},
...
});
After all the hard work, I was able the enjoy the result. The code ran smoothly as expected and was much better in term of structuring, semantic and maintainable criteria. I did not have to worry about later
maintaining/debugging process any more.
Conclusion
It may be a bit tedious to write all this code and structuring before implementing the real features. But for me it is really worthy, this pattern actually saves me a lot of time and effort trying to gure out where a function is,
what it does, how it connects to others functions.
If you are still using React version 0.14.3 in Meteor 1.2, which is possible if you already worked in these frameworks, I hope that you will get bene ted from my pattern and take the best of it.
If you are going to set up a new project with the latest version of React and Meteor and decide to implement this pattern, I would love to hear how you do that.