Flow Components
This project is still work in progress and does not have unit and integration tests. We are directly pushing changes to master. There's no plan to change current APIs, but we don't have a guarantee.
Build your Meteor app with Components.
Flow Components has borrowed a lot of concepts from React's component model and applies them on top Blaze. It's not a 1-to-1 mapping of React.
We've also added some handy features which will help you control reactivity when building a large application.
Table of Contents
- Why
- Getting Started
- States
- Actions
- Props
- Prototypes
- Extending Components with Mixins
- Extending Components with Nested Components
- Life Cycle Events
- Autoruns
- State Functions
- Content Blocks
- Referencing Child Components
- Refer All Child Components
- Organizing Large Components
- Accessing Component DOM
- How Flow Component different from XXX
- Usage Guidelines
Why?
When we started building Kadira.io, we had no idea how to architect a Meteor app. After working on it for almost 1.5 years, we realized we were doing it wrong.
So, we thought a lot and played with a lot of UI frameworks and concepts. That includes React and Flux. After a lot of iterations and experiments, Flow Components is our component framework which is a part of the Flow Architecture for Meteor.
Getting Started
Let's create a very simple component. It's a typical Hello World example.
First add Flow Components into your app.
meteor add meteorhacks:flow-components
Then create directory on the client directory of your Meteor app and put these files.
Here's the JavaScript file, (component.js
) which is the component.
1var component = FlowComponents.define('hello-component', function(props) { 2 console.log("A component created!"); 3 this.name = props.name; 4 5 this.setRandomGreeting(); 6 // change the greeting for every 300 millis 7 setInterval(this.setRandomGreeting.bind(this), 300); 8}); 9 10component.prototype.setRandomGreeting = function() { 11 var greetings = ["awesome", "nice", "cool", "kind"]; 12 var randomGreeting = greetings[Math.floor(greetings.length * Math.random())]; 13 this.set("greeting", randomGreeting) 14}; 15 16component.state.message = function() { 17 return this.name + ", you are " + this.get("greeting") + "!"; 18};
Now we need to create our template(view.html
). It's name should be identical to the name of the component which is hello-component
.
1<template name="hello-component"> 2 <div class="hello-component"> 3 Welcome Message: {{state$message}} 4 </div> 5</template>
Then, let's add a CSS file for our component.
1.hello-component { 2 font-family: 'Helvetica Neue', Helvetica, 'Segoe UI', Arial; 3 font-size: 16px; 4 margin: 10px; 5}
That's all. We've created our first component. We can render it anywhere we like. Here's how to do it.
1{{> render component="hello-component" name="Arunoda"}} 2{{> render component="hello-component" name="Sacha"}}
Then, this is how it's looks like:
Check this repo for the complete source code.
States
State is a variable which is reactive. It can hold any JavaScript literal or an object. This is very similar to a template helper, but it's integrated into the component.
There are couple of ways, you can get a state. This is the first way.
Creating states using component.state.
1var component = FlowComponents.define('my-component'); 2component.state.message = function() { 3 return "some value"; 4};
Above function is running in a reactive context. So, you can use any kind of reactive variables, Session variables and MiniMongo APIs inside it.
Context of the above function is the component itself. That's the main difference from a template helper.
Creating states using this.set
You can also set an state with this.set
API. This is an API of the component. So, you can use it anywhere withing the component. This is how to implement the above example via this.set
.
1var component = FlowComponents.define('my-component', function() { 2 this.set("message", "some value"); 3});
this.set
with large object
this.set
is a useful function, but it does value cloning and eqaulity checks. So, if you need to set a very large object this will be an issue.
But there is a solution to avoid that. Here's how to do it:
1var component = FlowComponents.define('my-component', function(params) { 2 var fireAway = true; 3 this.set("veryLargeObject", params.obj, fireAway); 4});
Now, flow component does not do any cloning or equality checks. It simply invalidate all the computations looks for this key.
Accessing states inside a template
You can access the state anywhere in the template as below:
1<template name='my-component'> 2 Message is: {{ state$message }} 3</template>
To access the state, just prefix it with state$
. You can even access the state inside nested templates in a given component.
Accessing states inside a component with this.get
You can also access the state inside the component with this this.get
API like this:
1component.state.messageWithName = function() { 2 var message = this.get("message"); 3 return "Arunoda, " + message; 4};
this.get
is reactive and available anywhere inside the component.
Actions
Components don't handle DOM events directly. But a component has actions. You can think actions are a kind of way to trigger tasks. To handle DOM elements, you need to call an action within a template event.
This is how to create an action:
1var component = FlowComponents.define('my-component'); 2component.action.changeMessage = function(someValue) { 3 this.set("message", someValue); 4};
Context of the message is the component itself. You can also access reactive content inside that, but the action won't re-run again for a change in reactive content.
There are few ways to call an action. Let's look at them.
Via an DOM event handler
You can call an action inside an event handler. But, that event handler needs to be registered for a template of the given component. This is how to do that.
1Template['my-component'].events({ 2 "click button": function() { 3 var message = $('.textbox').val(); 4 FlowComponents.callAction("changeMessage", message); 5 } 6});
Via Props (aka: Action Passing)
You can also pass an action to a child component via props. Then the child component can call that action just like invoking a JavaScript function. This is how to do it.
Let's say we are rendering a component called input
inside our main component:
1{{> render component="input" onSubmit=action$changeMessage }}
Then inside the input
component, it calls the onSubmit
property like this:
1var component = FlowComponents.define("input", function(props) { 2 this.onSubmit = props.onSubmit; 3}); 4 5component.action.submitMessage = function(message) { 6 this.onSubmit(message); 7};
We also describe this method as "action passing". This is the basic building block for creating nested components.
Actions and Promises
We've have es6-promise support for Actions. When you call an actions either via FlowComponents.callAction
or action passing, you'll get a promise always. Based on that promise you can model your component.
Action definition, does not need to return a promise all the time. If you return a promise, Flow Component will pass it to the caller. If not, it'll create a empty promise.
See:
1var component = FlowComponents.define("input", function(props) { 2 this.onSubmit = props.onSubmit; 3}); 4 5component.action.submitMessage = function(message) { 6 var self = this; 7 self.set('loading', true); 8 9 var promise = this.onSubmit(message); 10 promise.catch(function(err) { 11 self.set('errorMessage', err.message); 12 }).then(function() { 13 self.set('loading', false); 14 }); 15};
Checkout this sample repo for a complete example.
Disable Promises Temporarily
Sometime we need to have actions simply sending the plain return rather than wrapping the return as a promise. For those scenarios, we can temporarily disable promise support like this.
1var component = FlowComponents.define("input", function(props) { 2 this.onNewTooltip = props.onNewTooltip; 3 this.dataFn = props.dataFn; 4 this.autorun(this.formatTooltips); 5}); 6 7component.prototype.formatTooltips = function() { 8 var data = this.dataFn(); 9 var formattedData = this.noPromises(function() { 10 var self = this; 11 return data.map(function(item) { 12 return self.onNewTooltip(item); 13 }); 14 }); 15 16 return formattedData; 17};
Props
Props is a way to pass values when rendering the component. A prop can be any valid JavaScript literal, object or a function. This is how to do it:
1{{> render component="input" text="This is great" }}
Then you can access it inside the component like this:
1var component = FlowComponents.define("input", function(props) { 2 console.log("Text is: ", props.text); 3});
You can set any number of props you like:
1{{> render component="input" 2 text="This is great" 3 backgroundColor="#736634" 4 fontSize=20 5}}
You can pass a state into a prop like this:
1{{> render component="input" text=state$message }}
We've previously talked about how to pass an action like this:
1{{> render component="input" onSubmit=action$message }}
Prototypes
A Prototype is very similar to a prototype is JavaScript. Prototype is a common function (or property) you can access anywhere inside a component. We've used prototypes in the component we wrote in the Getting Started section.
1var component = FlowComponents.define('hello-component', function(props) { 2 // see how we are using the prototype 3 this.setRandomGreeting(); 4 setInterval(this.setRandomGreeting.bind(this), 300); 5}); 6 7// This is a prototype 8component.prototype.setRandomGreeting = function() { 9 var greetings = ["awesome", "nice", "cool", "kind"]; 10 var randomGreeting = messages[Math.floor(messages.length * Math.random())]; 11 this.set("greeting", randomGreeting) 12};
In that, we've created a setRandomGreeting
prototype and call in when a component is creating.
We've also calling it for every 300 milliseconds via the setInterval
.
Extending Components with Mixins
Sometimes we create similar kind of components. Then, we've to copy and paste a lot of code including prototypes
, states
and actions
. It's a bad way to manage it.
That's why Mixins are going to help us. With mixins we can group a set of common code and extend it with an existing components. Let's say we need to add component level subscriptions to Flow, this is how to do it :)
1ComponentSubs = { 2 prototype: {}, 3 action: {}, 4 state: {} 5}; 6 7// calls when the component is creating 8ComponentSubs.created = function() { 9 this._subs = []; 10}; 11 12// calls when the component is rendered 13ComponentSubs.rendered = function() {}; 14 15// calls when the component is destroyed 16ComponentSubs.destroyed = function() { 17 this.stopSubscriptions(); 18}; 19 20ComponentSubs.prototype.subscribe = function() { 21 var sub = Meteor.subscribe.apply(null, arguments); 22 this._subs.push(sub); 23 return sub; 24}; 25 26ComponentSubs.prototype.ready = function() { 27 var ready = true; 28 this._subs.forEach(function(sub) { 29 ready = sub.ready(); 30 }); 31 32 return ready; 33}; 34 35ComponentSubs.prototype.stopSubscriptions = function() { 36 this._subs.forEach(function(sub) { 37 sub.stop(); 38 }); 39 this._subs = []; 40}; 41 42ComponentSubs.state.isReady = function() { 43 return this.ready(); 44}; 45 46ComponentSubs.action.stopSubscriptions = function() { 47 this.stopSubscriptions(); 48};
Now you can extend your component with the mixin we've created. Check this:
1var component = FlowComponents.define("my-component", function() { 2 // you can use like to this subscribe 3 this.subscribe("mysubscription"); 4}); 5 6// extend your component with Mixins 7component.extend(ComponentSubs); 8 9// you can use it in an action like this 10component.action.loadMore = function() { 11 this.stopSubscriptions(); 12 this.subscribe("mysubscription", {limit: 200}); 13};
You can use isReady
state inside the template like this:
1<template name="my-component"> 2 {{#if state$isReady}} 3 <!-- do something with your data --> 4 {{else}} 5 Loading... 6 {{/if}} 7</template>
Extending Components with Nested Components
We can use Mixins to extend the functionalities for the component. But we can't use that to extend the user interface. That's where we can use nested components.
There is no special APIs for that. But you can create a component which uses few other components inside that.
You can also accept an component name from the props
and render that. For an example, let's say we are building a loading component. So, we can allow to customize the loading spinner. Here is is:
1var component = FlowComponents.define("loading", function(props) { 2 this.set("loadingComponent", props.loadingComponent); 3});
This is the UI for that:
1{{#if state$loadingComponent}} 2 {{> render component=state$loadingComponent }} 3{{else}} 4 Loading... 5{{/if}}
Life Cycle Events
A Component has few different events. Here they are:
- created - After the component instant created
- rendered - After the component rendered to the screen
- destroyed - After the component destroyed
You may need to use these events to customize your components. We need to use the created event almost every time. So, that's the callback you passed as the second argument when creating the components.
1var component = FlowComponents.define("hello", function(props) { 2 console.log("Component created with props:", props); 3});
In the created
event callback you can get the props
as the first argument.
For other two events, they can be access anywhere inside the component like with:
- rendered -
this.onRendered(function() {})
- destroyed -
this.onDestroyed(function() {})
Check this example:
1var component = FlowComponents.define("hello", function() { 2 this.onRendered(function() { 3 console.log("Rendered to the screen."); 4 }); 5 6 this.onDestroyed(function() { 7 console.log("Component destroyed."); 8 }); 9});
Context of the callback you've passed to a life cycle event is the component itself. So, because of that something like this is possible.
1var component = FlowComponents.define("hello", function() { 2 this.onRendered(function() { 3 console.log("Rendered to the screen."); 4 5 this.onDestroyed(function() { 6 console.log("Component destroyed."); 7 }); 8 }); 9});
Autoruns
Sometimes we may need to use autoruns inside a component. So, when you start an autorun it needs to stop when the component destroyed. We've a simple way to do that. See:
1var component = FlowComponents.define("hello", function() { 2 this.autorun(function() { 3 var posts = Posts.fetch(); 4 this.set("postCount", posts.length); 5 }); 6});
Note: Context of the callback for
this.autorun
is also the component. That's why callingthis.set
is possible inside the autorun.
State Functions
State functions is a powerful tool which helps you build components while minimizing re-renders. Before we start, let's see why need it. Look at this usage of nested components:
1var component = FlowComponents.define("parent", function() { 2 var self = this; 3 setInterval(function() { 4 var usage = Math.ceil(Math.random() * 100); 5 this.set("cpuUsage", usage); 6 }, 100); 7});
This is the template of parent:
1<template name="parent"> 2 {{> render component="gauge" value=state$cpuUsage }} 3</template>
As you can see this is pretty straight forward. Parent component change the CPU usage for every 100 millis and then guage
component will print it. So, what's the issue here?
Since we get the state as state$cpuUsage
, it's getting change every 100 millis. So, the gauge
component will get changed at that time too.
That means existing gauge component will be destroyed and re created again. Which is very expensive and we don't need to do something like this. That's where state functions are going to help you. Before that, let's look at how we've implemented our gauge component.
1var component = FlowComponents.define("guage", function(props) { 2 this.set('value', props.value); 3});
This is the template:
1<template name="guage"> 2 Value is: {{ state$value }} 3</template>
Converting it to use State Functions
Let's change the parent template like this:
1<template name="parent"> 2 {{> render component="gauge" value=stateFn$cpuUsage }} 3</template>
Note that, we only change state$cpuUsage
into stateFn$cpuUsage
. With that, we wrap the cpuUsage
state into a function. So, when it's get changed, it won't re-render the component.
This is how to access the state it inside the gauge
component.
1var component = FlowComponents.define("guage", function(props) { 2 this.autorun(function() { 3 // see now it's a function 4 var value = props.value(); 5 this.set("value", value); 6 }); 7});
As you can see, now value
prop is a function. Now it's only reactive within the autorun we've defined. So, now we can actually, control the reactivity as we need.
Writing this.autorun
for every prop seems like a boring task. That's why we introduced this.setFn
. See how to use it. It does the exact same thing we did in the previous example.
1var component = FlowComponents.define("guage", function(props) { 2 this.setFn("value", props.value); 3});
Content Blocks
We can use content blocks to write nested components. Here's an example for a loading component which uses content blocks.
1{{#render component="loading" loaded=stateFn$loaded }} 2 {{>render component="data-viewer"}} 3{{else}} 4 Loading... 5{{/render}}
This is how we can implement the loading
component
1var component = FlowComponents.define('loading', function(props) { 2 this.setFn("loaded", props.loaded); 3});
Here's the template:
1<template name="loading"> 2 {{#if state$loaded}} 3 {{> flowContentBlock }} 4 {{else}} 5 {{> flowElseBlock }} 6 {{/if}} 7</template>
Referencing Child Components
This API is experimental.
So, now we know how to use child components and we've seen some examples. Most of the time you can interact with them by passing actions and passing state functions.
But sometimes, you may need to refer them individually access their states. Let's look at our myForm component.
1var component = FlowComponents.define("myForm", function() { 2 3}); 4 5component.action.updateServer = function(name, address) { 6 Meteor.call("update-profile", name, address); 7};
This is the template for myForm.
1<template name="myFrom"> 2 {{> render component="input" id="name" }} 3 {{> render component="input" id="address" }} 4 <button>Submit</button> 5</template>
Here's the event handler for submit.
1Template['myForm'].events({ 2 "click button": function() { 3 var name = FlowComponents.child("name").getState("value"); 4 var address = FlowComponents.child("address").getState("value"); 5 6 FlowComponents.callAction('updateServer', name, address); 7 } 8});
See, we could access individual child component by their id and get the state called value. But this API has following characteristics:
- You can only access child components inside template helpers and event handlers only.
- You can't access it inside the component. (We add this restriction to avoid unnecessary re-renders)
- Unlike an "id" in CSS, here "id" is scope to a component. You can have child components with the same id in few different components.
- You can nest child lookups.
Refer All Child Components
This API is experimental.
This API is just like FlowComponents.child()
, but it gives all the child components inside the current component.
1var allChildComponents = FlowComponents.children(); 2allChildComponents.forEach(function(child) { 3 console.log(child.getState("value")); 4});
Organizing Large Components
Sometimes our components could have a large number of states, actions and prototypes. So, it's super hard to put them all in a single file. Luckily, there's a way to put those functions in different files. This is how to do it.
First create the component and name it like component.js
1var component = FlowComponents.define("myForm", function() { 2 3});
Then create a file for states
with the name component_states.js
.
1var component = FlowComponents.find("myForm"); 2component.state.title = function() { 3 4};
It's very important to define the component before accessing it using .find()
. That's why we've a naming convention like above.
Likewise you can group actions
, states
and prototypes
in anyway you like organize your component.
Accessing Component DOM
We've designed components in a way that to reduce the direct interfacing with the DOM. But in practice, it's hard to do. So, if you want to access the DOM directly inside the component, here are the APIs for that. All these API are scoped to the template of the component.
- this.$(selector) - get a jQuery object for the given selector
- this.find(selector) - get a one matching element for the given selector
- this.findAll(selector) - get all matching elements to the given selector
How Flow Components different from XXX
Let's compare flow with some other components and UI related frameworks
Blaze
Flow Component does not replace or Blaze. Instead it's build on top of the Blaze. We are using Blaze templates to render the user interfaces. When using Flow Components, you may don't need to use template helpers and template instances anymore. But still, we use a lot of cool features of Blaze.
React
React is a completely different UI framework. There is no built in support for React with flow components. But, there are a few ways to integrate React with Meteor. Flow does not interfere with them.
If there is a way to render react components inside a Blaze template, then it's possible to use React with Flow. That's because we are using Blaze templates to render the UI.
Polymer / WebComponents
Answer for this is just the same as for React.
Ionic / Meteoric
Answer for this is just the same as for React.
Angular
It might be possible to use Angular with Flow Components. But we haven't try that yet.
Blaze 2
There is an ongoing proposal for Blaze 2. It has an it's own component system. It's still in the design phase. Try to look at it.
We designed Flow Components for our internal use at MeteorHacks. We've build few projects with Flow. So, it's unlikely we'll switch to a new component system unless it has all of our features.
Usage Guidelines
We use Flow Components alot at MeteorHacks specially on Kadira and BulletProof Meteor. We follow some simple rules to manage components and do inter component communication.
Here are the guidelines: https://meteorhacks.hackpad.com/Flow-Components-Guideline-gAn4odmDRw3