SlideShare uma empresa Scribd logo
1 de 5
Baixar para ler offline
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
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.
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:
// 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
]);
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.

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Intro to ReactJS
Intro to ReactJSIntro to ReactJS
Intro to ReactJS
 
Academy PRO: React JS
Academy PRO: React JSAcademy PRO: React JS
Academy PRO: React JS
 
ReactJS for Beginners
ReactJS for BeginnersReactJS for Beginners
ReactJS for Beginners
 
Reactjs
Reactjs Reactjs
Reactjs
 
React js
React jsReact js
React js
 
React, Flux and a little bit of Redux
React, Flux and a little bit of ReduxReact, Flux and a little bit of Redux
React, Flux and a little bit of Redux
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
Getting Started with React-Nathan Smith
Getting Started with React-Nathan SmithGetting Started with React-Nathan Smith
Getting Started with React-Nathan Smith
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
 
Let's Redux!
Let's Redux!Let's Redux!
Let's Redux!
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
React and Flux life cycle with JSX, React Router and Jest Unit Testing
React and  Flux life cycle with JSX, React Router and Jest Unit TestingReact and  Flux life cycle with JSX, React Router and Jest Unit Testing
React and Flux life cycle with JSX, React Router and Jest Unit Testing
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
React render props
React render propsReact render props
React render props
 
Introduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace ITIntroduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace IT
 
React js
React jsReact js
React js
 
Getting Started With ReactJS
Getting Started With ReactJSGetting Started With ReactJS
Getting Started With ReactJS
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 

Destaque

Kuali Identity Management - Introduction And Implementation Options
Kuali Identity Management - Introduction And Implementation OptionsKuali Identity Management - Introduction And Implementation Options
Kuali Identity Management - Introduction And Implementation OptionsEric Westfall
 
React Component Library Design @WalmartLabs
React Component Library Design @WalmartLabsReact Component Library Design @WalmartLabs
React Component Library Design @WalmartLabschaseadamsio
 
React js - Component specs and lifecycle
React js - Component specs and lifecycleReact js - Component specs and lifecycle
React js - Component specs and lifecycleDoanh PHAM
 
proceso productivo de la lana
 proceso productivo de la lana proceso productivo de la lana
proceso productivo de la lanajordanpoza8a
 
Ajkai Szó 2016.11.04.
Ajkai Szó 2016.11.04.Ajkai Szó 2016.11.04.
Ajkai Szó 2016.11.04.Ajkai Szó
 
Kehittämisrahoitus - Opioidikorvaushoidon verkostopäivät 2016
Kehittämisrahoitus - Opioidikorvaushoidon verkostopäivät 2016Kehittämisrahoitus - Opioidikorvaushoidon verkostopäivät 2016
Kehittämisrahoitus - Opioidikorvaushoidon verkostopäivät 2016THL
 
Presentacion aulas virtuales y correo institucional
Presentacion aulas virtuales y correo institucionalPresentacion aulas virtuales y correo institucional
Presentacion aulas virtuales y correo institucionalfernandofonseca777
 
OK-hanke - Mistä on kyse?
OK-hanke - Mistä on kyse?OK-hanke - Mistä on kyse?
OK-hanke - Mistä on kyse?THL
 
Kyoorius Designyatra | Kaliber Interactive | This brave new world needs Tommy
Kyoorius Designyatra | Kaliber Interactive | This brave new world needs TommyKyoorius Designyatra | Kaliber Interactive | This brave new world needs Tommy
Kyoorius Designyatra | Kaliber Interactive | This brave new world needs TommyKaliber Interactive
 
Perulangan atau looping dalam java
Perulangan atau looping dalam javaPerulangan atau looping dalam java
Perulangan atau looping dalam javaWahyu Ardiyono
 
Proceso del desarrollo humano
Proceso del desarrollo humanoProceso del desarrollo humano
Proceso del desarrollo humanojuanchitoxx00
 

Destaque (16)

Kuali Identity Management - Introduction And Implementation Options
Kuali Identity Management - Introduction And Implementation OptionsKuali Identity Management - Introduction And Implementation Options
Kuali Identity Management - Introduction And Implementation Options
 
React Component Library Design @WalmartLabs
React Component Library Design @WalmartLabsReact Component Library Design @WalmartLabs
React Component Library Design @WalmartLabs
 
React js - Component specs and lifecycle
React js - Component specs and lifecycleReact js - Component specs and lifecycle
React js - Component specs and lifecycle
 
Using redux
Using reduxUsing redux
Using redux
 
B3-Project
B3-ProjectB3-Project
B3-Project
 
Algarabia
AlgarabiaAlgarabia
Algarabia
 
proceso productivo de la lana
 proceso productivo de la lana proceso productivo de la lana
proceso productivo de la lana
 
Ajkai Szó 2016.11.04.
Ajkai Szó 2016.11.04.Ajkai Szó 2016.11.04.
Ajkai Szó 2016.11.04.
 
Kehittämisrahoitus - Opioidikorvaushoidon verkostopäivät 2016
Kehittämisrahoitus - Opioidikorvaushoidon verkostopäivät 2016Kehittämisrahoitus - Opioidikorvaushoidon verkostopäivät 2016
Kehittämisrahoitus - Opioidikorvaushoidon verkostopäivät 2016
 
Presentacion aulas virtuales y correo institucional
Presentacion aulas virtuales y correo institucionalPresentacion aulas virtuales y correo institucional
Presentacion aulas virtuales y correo institucional
 
161103 - FFBB Infos 082
161103 - FFBB Infos 082161103 - FFBB Infos 082
161103 - FFBB Infos 082
 
Lilly North
Lilly NorthLilly North
Lilly North
 
OK-hanke - Mistä on kyse?
OK-hanke - Mistä on kyse?OK-hanke - Mistä on kyse?
OK-hanke - Mistä on kyse?
 
Kyoorius Designyatra | Kaliber Interactive | This brave new world needs Tommy
Kyoorius Designyatra | Kaliber Interactive | This brave new world needs TommyKyoorius Designyatra | Kaliber Interactive | This brave new world needs Tommy
Kyoorius Designyatra | Kaliber Interactive | This brave new world needs Tommy
 
Perulangan atau looping dalam java
Perulangan atau looping dalam javaPerulangan atau looping dalam java
Perulangan atau looping dalam java
 
Proceso del desarrollo humano
Proceso del desarrollo humanoProceso del desarrollo humano
Proceso del desarrollo humano
 

Semelhante a React – Structure Container Component In Meteor

Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksKaty Slemon
 
OttawaJS - React
OttawaJS - ReactOttawaJS - React
OttawaJS - Reactrbl002
 
Corso su ReactJS
Corso su ReactJSCorso su ReactJS
Corso su ReactJSLinkMe Srl
 
Thinking in Components
Thinking in ComponentsThinking in Components
Thinking in ComponentsFITC
 
React Hooks Demystified: How to Effectively Use useCallback and useEffect
React Hooks Demystified: How to Effectively Use useCallback and useEffectReact Hooks Demystified: How to Effectively Use useCallback and useEffect
React Hooks Demystified: How to Effectively Use useCallback and useEffectTien Nguyen
 
30 days-of-react-ebook-fullstackio
30 days-of-react-ebook-fullstackio30 days-of-react-ebook-fullstackio
30 days-of-react-ebook-fullstackioimdurgesh
 
Exploring Hooks in React
Exploring Hooks in ReactExploring Hooks in React
Exploring Hooks in ReactTien Nguyen
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with trackerDesignveloper
 
A React Journey
A React JourneyA React Journey
A React JourneyLinkMe Srl
 
The complete-beginners-guide-to-react dyrr
The complete-beginners-guide-to-react dyrrThe complete-beginners-guide-to-react dyrr
The complete-beginners-guide-to-react dyrrAfreenK
 
Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...Katy Slemon
 
ReactCodemod: An automated approach for refactoring class based components to...
ReactCodemod: An automated approach for refactoring class based components to...ReactCodemod: An automated approach for refactoring class based components to...
ReactCodemod: An automated approach for refactoring class based components to...IRJET Journal
 
Welcome to React & Flux !
Welcome to React & Flux !Welcome to React & Flux !
Welcome to React & Flux !Ritesh Kumar
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today Nitin Tyagi
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]GDSC UofT Mississauga
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 

Semelhante a React – Structure Container Component In Meteor (20)

Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooks
 
OttawaJS - React
OttawaJS - ReactOttawaJS - React
OttawaJS - React
 
ReactJS (1)
ReactJS (1)ReactJS (1)
ReactJS (1)
 
Corso su ReactJS
Corso su ReactJSCorso su ReactJS
Corso su ReactJS
 
Thinking in Components
Thinking in ComponentsThinking in Components
Thinking in Components
 
React Hooks Demystified: How to Effectively Use useCallback and useEffect
React Hooks Demystified: How to Effectively Use useCallback and useEffectReact Hooks Demystified: How to Effectively Use useCallback and useEffect
React Hooks Demystified: How to Effectively Use useCallback and useEffect
 
30 days-of-react-ebook-fullstackio
30 days-of-react-ebook-fullstackio30 days-of-react-ebook-fullstackio
30 days-of-react-ebook-fullstackio
 
Exploring Hooks in React
Exploring Hooks in ReactExploring Hooks in React
Exploring Hooks in React
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
 
A React Journey
A React JourneyA React Journey
A React Journey
 
The complete-beginners-guide-to-react dyrr
The complete-beginners-guide-to-react dyrrThe complete-beginners-guide-to-react dyrr
The complete-beginners-guide-to-react dyrr
 
Lec7Handout.ppt
Lec7Handout.pptLec7Handout.ppt
Lec7Handout.ppt
 
Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...
 
ReactCodemod: An automated approach for refactoring class based components to...
ReactCodemod: An automated approach for refactoring class based components to...ReactCodemod: An automated approach for refactoring class based components to...
ReactCodemod: An automated approach for refactoring class based components to...
 
Welcome to React & Flux !
Welcome to React & Flux !Welcome to React & Flux !
Welcome to React & Flux !
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
React
ReactReact
React
 

Mais de Designveloper

Let us take care of your brand image
Let us take care of your brand imageLet us take care of your brand image
Let us take care of your brand imageDesignveloper
 
5 java script frameworks to watch in 2017
5 java script frameworks to watch in 20175 java script frameworks to watch in 2017
5 java script frameworks to watch in 2017Designveloper
 
Happy international women's day!
Happy international women's day!Happy international women's day!
Happy international women's day!Designveloper
 
Typing racer game - a nice break from work
Typing racer game  - a nice break from workTyping racer game  - a nice break from work
Typing racer game - a nice break from workDesignveloper
 
Should we work remotely?
Should we work remotely?Should we work remotely?
Should we work remotely?Designveloper
 
Meet song nhi your virtual financial assistance
Meet song nhi   your virtual financial assistanceMeet song nhi   your virtual financial assistance
Meet song nhi your virtual financial assistanceDesignveloper
 
Why pair programming is a good idea
Why pair programming is a good idea Why pair programming is a good idea
Why pair programming is a good idea Designveloper
 
5 worst mistakes of diy websites
5 worst mistakes of diy websites5 worst mistakes of diy websites
5 worst mistakes of diy websitesDesignveloper
 
Basic glossary of web design terms for non designers (part 2)
Basic glossary of web design terms for non designers (part 2)Basic glossary of web design terms for non designers (part 2)
Basic glossary of web design terms for non designers (part 2)Designveloper
 
Single page web application development using meteor js
Single page web application development using meteor jsSingle page web application development using meteor js
Single page web application development using meteor jsDesignveloper
 
Multiplayer game with unity3 d and meteor
Multiplayer game with unity3 d and meteorMultiplayer game with unity3 d and meteor
Multiplayer game with unity3 d and meteorDesignveloper
 
Awesome free resources for learning javascript
Awesome free resources for learning javascriptAwesome free resources for learning javascript
Awesome free resources for learning javascriptDesignveloper
 
What is the best java script frameworks to learn?
What is the best java script frameworks to learn?What is the best java script frameworks to learn?
What is the best java script frameworks to learn?Designveloper
 
Travelling forms a young man
Travelling forms a young manTravelling forms a young man
Travelling forms a young manDesignveloper
 
5 compelling reasons your website should be responsive
5 compelling reasons your website should be responsive5 compelling reasons your website should be responsive
5 compelling reasons your website should be responsiveDesignveloper
 
Benefits of using single page websites
Benefits of using single page websitesBenefits of using single page websites
Benefits of using single page websitesDesignveloper
 
What is the best programming language for beginner?
What is the best programming language for beginner?What is the best programming language for beginner?
What is the best programming language for beginner?Designveloper
 
No sql injection in meteor.js application
No sql injection in meteor.js applicationNo sql injection in meteor.js application
No sql injection in meteor.js applicationDesignveloper
 
How to deploy and scale your meteor apps
How to deploy and scale your meteor appsHow to deploy and scale your meteor apps
How to deploy and scale your meteor appsDesignveloper
 
Meetup groups you need to join if you are new to tech
Meetup groups you need to join if you are new to techMeetup groups you need to join if you are new to tech
Meetup groups you need to join if you are new to techDesignveloper
 

Mais de Designveloper (20)

Let us take care of your brand image
Let us take care of your brand imageLet us take care of your brand image
Let us take care of your brand image
 
5 java script frameworks to watch in 2017
5 java script frameworks to watch in 20175 java script frameworks to watch in 2017
5 java script frameworks to watch in 2017
 
Happy international women's day!
Happy international women's day!Happy international women's day!
Happy international women's day!
 
Typing racer game - a nice break from work
Typing racer game  - a nice break from workTyping racer game  - a nice break from work
Typing racer game - a nice break from work
 
Should we work remotely?
Should we work remotely?Should we work remotely?
Should we work remotely?
 
Meet song nhi your virtual financial assistance
Meet song nhi   your virtual financial assistanceMeet song nhi   your virtual financial assistance
Meet song nhi your virtual financial assistance
 
Why pair programming is a good idea
Why pair programming is a good idea Why pair programming is a good idea
Why pair programming is a good idea
 
5 worst mistakes of diy websites
5 worst mistakes of diy websites5 worst mistakes of diy websites
5 worst mistakes of diy websites
 
Basic glossary of web design terms for non designers (part 2)
Basic glossary of web design terms for non designers (part 2)Basic glossary of web design terms for non designers (part 2)
Basic glossary of web design terms for non designers (part 2)
 
Single page web application development using meteor js
Single page web application development using meteor jsSingle page web application development using meteor js
Single page web application development using meteor js
 
Multiplayer game with unity3 d and meteor
Multiplayer game with unity3 d and meteorMultiplayer game with unity3 d and meteor
Multiplayer game with unity3 d and meteor
 
Awesome free resources for learning javascript
Awesome free resources for learning javascriptAwesome free resources for learning javascript
Awesome free resources for learning javascript
 
What is the best java script frameworks to learn?
What is the best java script frameworks to learn?What is the best java script frameworks to learn?
What is the best java script frameworks to learn?
 
Travelling forms a young man
Travelling forms a young manTravelling forms a young man
Travelling forms a young man
 
5 compelling reasons your website should be responsive
5 compelling reasons your website should be responsive5 compelling reasons your website should be responsive
5 compelling reasons your website should be responsive
 
Benefits of using single page websites
Benefits of using single page websitesBenefits of using single page websites
Benefits of using single page websites
 
What is the best programming language for beginner?
What is the best programming language for beginner?What is the best programming language for beginner?
What is the best programming language for beginner?
 
No sql injection in meteor.js application
No sql injection in meteor.js applicationNo sql injection in meteor.js application
No sql injection in meteor.js application
 
How to deploy and scale your meteor apps
How to deploy and scale your meteor appsHow to deploy and scale your meteor apps
How to deploy and scale your meteor apps
 
Meetup groups you need to join if you are new to tech
Meetup groups you need to join if you are new to techMeetup groups you need to join if you are new to tech
Meetup groups you need to join if you are new to tech
 

Último

Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 

Último (20)

Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 

React – Structure Container Component In Meteor

  • 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.