React

How to use React, Facebook's frontend rendering library, with Meteor.

After reading this guide, you’ll know:

  • What React is, and why you would consider using it with Meteor.
  • How to install React in your Meteor application, and how to use it correctly.
  • How to integrate React with Meteor’s realtime data layer.
  • How to route in a React/Meteor application.

Introduction

React is a JavaScript library for building reactive user interfaces developed and distributed by the Facebook team. React is one of the three rendering libraries supported by Meteor; the alternatives are Blaze and Angular. Here’s a comparison of all three.

React has a vibrant and growing ecosystem and is used widely in production in a variety of combinations with different frameworks.

To learn more about using React in general and coming up to speed with the library, you should check out the React documentation, especially the thinking in React post, which explains the React philosophy well.

To get started with React in Meteor, you can follow along the React tutorial. To see an example of a more complete Meteor application built with React, check out the react branch of the Todos example application. Where applicable, code examples in this article will reference that app.

Installing and using React

To install React in Meteor 1.3 you should add it as an npm dependency:

  1. meteor npm install --save react react-dom

This will install react into your project and allow you to access it within your files with import React from 'react'. Most React code is written in JSX, which you can use by default in Meteor if you include the ecmascript package (which is installed in all Meteor apps by default).

  1. import React from 'react';
  2. export default class HelloWorld extends React.Component {
  3. render() {
  4. return (
  5. <h1>Hello World</h1>
  6. );
  7. }
  8. }

You can render a component hierarchy to the DOM using the react-dom package:

  1. import { Meteor } from 'meteor/meteor';
  2. import React from 'react';
  3. import { render } from 'react-dom';
  4. import HelloWorld from './HelloWorld.js';
  5. Meteor.startup(() => {
  6. render(<HelloWorld />, document.getElementById('app'));
  7. });

You need to include a <div id="app"></div> in your body’s HTML somewhere of course.

Every new Meteor app includes Blaze, Meteor’s default templating system, by default. If you are not planning on using React and Blaze together, you can remove Blaze from your project by running:

  1. meteor remove blaze-html-templates
  2. meteor add static-html

Using 3rd party packages

If you’d like to use a third party React component that has been published on npm, you can meteor npm install —save them and import from within your app.

For example, to use the excellent Griddle React package for making tables, you could run

  1. meteor npm install --save griddle-react

Then, like with any other npm package, you can import the component in your application:

  1. import React from 'react';
  2. import Griddle from 'griddle-react';
  3. export default class MyGriddler extends React.Component {
  4. render() {
  5. return (<Griddle ..../>);
  6. }
  7. }

If you are looking to write an Atmosphere package that wraps such a component, you need to take some further steps.

React Components in Blaze

If you’d like to use React within a larger app built with Blaze (which is a good strategy if you’d like to incrementally migrate an app from Blaze to React), you can use the react-template-helper component which renders a react component inside a Blaze template. First run meteor add react-template-helper, then use the React helper in your template:

  1. <template name="userDisplay">
  2. <div>Hello, {{username}}</div>
  3. <div>{{> React component=UserAvatar userId=_id}}</div>
  4. </template>

You will need to pass in the component class with a helper:

  1. import { Template } from 'meteor/templating';
  2. import './userDisplay.html';
  3. import UserAvatar from './UserAvatar.js';
  4. Template.userDisplay.helpers({
  5. UserAvatar() {
  6. return UserAvatar;
  7. }
  8. })

The component argument is the React component to include, which should be passed in with a helper.

Every other argument is passed as a prop to the component when it is rendered.

Note that there a few caveats:

  • React components must be the only thing in the wrapper element. Due to a limitation of React (see facebook/react #1970, #2484), a React component must be rendered as the only child of its parent node, meaning it cannot have any siblings.

  • This means a React component also can’t be the only thing in a Blaze template, because it’s impossible to tell where the template will be used.

Passing callbacks to a React component

To pass a callback to a React component that you are including with this helper, make a template helper that returns a function, and pass it in as a prop, like so:

  1. Template.userDisplay.helpers({
  2. onClick() {
  3. const instance = Template.instance();
  4. // Return a function from this helper, where the template instance is in
  5. // a closure
  6. return () => {
  7. instance.hasBeenClicked.set(true)
  8. }
  9. }
  10. });

To use it in Blaze:

  1. <template name="userDisplay">
  2. <div>
  3. {{> React component=UserAvatar userId=_id onClick=onClick}}
  4. </div>
  5. </template>

Blaze Templates in React

We can also use Blaze templates in React components. This is similarly useful for a gradual transition strategy; but more importantly, it allows us to continue to use the multitude of Atmosphere packages built for Blaze in our React projects, as well as core packages like accounts-ui.

One way to do this is with the gadicc:blaze-react-component package. First run meteor add gadicc:blaze-react-component, then import and use it in your components as follows:

  1. import React from 'react';
  2. import Blaze from 'meteor/gadicc:blaze-react-component';
  3. const App = () => (
  4. <div>
  5. <Blaze template="itemsList" items={items} />
  6. </div>
  7. );

The <Blaze template="itemsList" items={items} /> line is the same as if you had written {{> itemsList items=items}} inside of a Blaze template. For other options and further information, see the package’s project page.

Using Meteor’s data system

React is a front-end rendering library and as such doesn’t concern itself with how data gets into and out of components. On the other hand, Meteor has strong opinions about data! Meteor operates in terms of publications and methods, used to subscribe to and modify the data in your application.

To integrate the two systems, we’ve developed a react-meteor-data package which allows React components to respond to data changes via Meteor’s Tracker reactivity system.

Using withTracker

The withTracker function now replaces the previous function createContainer, however it remains as part of the package for backwards compatibility.

To use data from a Meteor collection inside a React component, install react-meteor-data:

  1. meteor add react-meteor-data

Once installed, you’ll be able to import the withTracker function, which allows you to create a container component which provides data to your presentational components.

Note that “container components” are analogous to the “smart components” and “presentational components” to the “reusable components” in the pattern we document in the UI/UX article, if you’d like to read more about how this philosophy relates to Meteor.

For example, in the Todos example app, we have a ListPage component, which renders list metadata and the tasks in the list. In order to do so, it needs to subscribe to the todos.inList publication, check that subscription’s readiness, then fetch the list of todos from the Todos collection.

It also needs to be responsive to reactive changes in the state of those actions (for instance if a todo changes due to the action of another user). All this data loading complexity is a typical use-case for a container-presentational component split, and the withTracker function makes this possible.

We define the ListPage component as a presentational component that expects its data to be passed in using React props:

  1. import React from 'react';
  2. export default class ListPage extends React.Component {
  3. ...
  4. }
  5. ListPage.propTypes = {
  6. list: React.PropTypes.object,
  7. todos: React.PropTypes.array,
  8. loading: React.PropTypes.bool,
  9. listExists: React.PropTypes.bool,
  10. };

Then we create a container component which wraps it and provides a data source:

  1. import { Meteor } from 'meteor/meteor';
  2. import { Lists } from '../../api/lists/lists.js';
  3. import { withTracker } from 'meteor/react-meteor-data';
  4. import ListPage from '../pages/ListPage.js';
  5. const ListPageContainer = withTracker(({ id }) => {
  6. const todosHandle = Meteor.subscribe('todos.inList', id);
  7. const loading = !todosHandle.ready();
  8. const list = Lists.findOne(id);
  9. const listExists = !loading && !!list;
  10. return {
  11. loading,
  12. list,
  13. listExists,
  14. todos: listExists ? list.todos().fetch() : [],
  15. };
  16. })(ListPage);
  17. export default ListPageContainer;

If you’re subscribing to multiple publications, you can create an array of handles and use some to determine if any is loading:

  1. export default withTracker(({ id }) => {
  2. const handles = [
  3. Meteor.subscribe('todos.inList', id),
  4. Meteor.subscribe('otherSub'),
  5. ];
  6. const loading = handles.some(handle => !handle.ready());
  7. return {
  8. loading,
  9. };
  10. })(ListPage);

It’s a good habit to name your container exactly like the component that it wraps, with the word “Container” tacked onto the end (eg ListPageContainer). This way, when you’re attempting to track down issues in your code, it makes it much easier to locate the appropriate files/classes.

The container component created by withTracker will reactively re-render the wrapped component in response to any changes to reactive data sources accessed from inside the function provided to it.

Although this ListPageContainer container is intended to be instantiated by the React Router (which passes in the props automatically), if we did ever want to create one manually, we would need to pass in the props to the container component (which then get passed into our data function above):

  1. <ListPageContainer id={7}/>

Preventing re-renders

Sometimes changes in your data can trigger re-computations which you know won’t affect your UI. Although React is in general quite efficient in the face of unnecessary re-renders, if you need to control re-rendering, the above pattern allows you to use React’s shouldComponentUpdate on the presentational component to avoid re-renders.

Routing

There are two main options for routing with Meteor and React. Either way, we recommend consulting our Routing article for some general principles of routing in Meteor before writing your app.

  • kadira:flow-router is a Meteor specific router that can be used both with React and Blaze. It is documented in detail in the Routing article.

  • react-router is a React-specific router very popular in the React community. It can also be used with Meteor.

Flow Router

Using Flow Router with React is very similar to using it with Blaze. The only difference is that in your route actions, you should use the react-mounter package to mount components with a layout. Once you meteor npm install —save react-mounter, you can do the following:

  1. import React from 'react';
  2. import { FlowRouter } from 'meteor/kadira:flow-router';
  3. import { mount } from 'react-mounter';
  4. import AppContainer from '../../ui/containers/AppContainer.js';
  5. import ListPageContainer from '../../ui/containers/ListPageContainer.js';
  6. FlowRouter.route('/lists/:_id', {
  7. name: 'Lists.show',
  8. action() {
  9. mount(AppContainer, {
  10. main: <ListPageContainer/>,
  11. });
  12. },
  13. });

Note that react-mounter automatically mounts the layout component on a #react-root node, which you can change by using the withOptions() function.

In the below example, your App component would receive a main prop with a instantiated React Element to render:

  1. const App = (props) => (
  2. <div>
  3. <section id="menu"><..></section>
  4. {props.main}
  5. </div>
  6. );
  7. const AppContainer = withTracker(props => {
  8. // props here will have `main`, passed from the router
  9. // anything we return from this function will be *added* to it
  10. return {
  11. user: Meteor.user(),
  12. };
  13. })(App);
  14. export default AppContainer;

React Router

Using React Router is also straightforward. Once you meteor npm install —save react-router history, you can export a list of nested routes as you would in any other React Router driven React application:

  1. import React from 'react';
  2. import { Router, Route, Switch } from 'react-router';
  3. import createBrowserHistory from 'history/createBrowserHistory';
  4. // route components
  5. import AppContainer from '../../ui/containers/AppContainer.js';
  6. import ListPageContainer from '../../ui/containers/ListPageContainer.js';
  7. import AuthPageSignIn from '../../ui/pages/AuthPageSignIn.js';
  8. import AuthPageJoin from '../../ui/pages/AuthPageJoin.js';
  9. import NotFoundPage from '../../ui/pages/NotFoundPage.js';
  10. const browserHistory = createBrowserHistory();
  11. export const renderRoutes = () => (
  12. <Router history={browserHistory}>
  13. <Switch>
  14. <Route exact path="/" component={AppContainer}/>
  15. <Route exact path="/lists/:id" component={ListPageContainer}/>
  16. <Route exact path="/signin" component={AuthPageSignIn}/>
  17. <Route exact path="/join" component={AuthPageJoin}/>
  18. <Route component={NotFoundPage}/>
  19. </Switch>
  20. </Router>
  21. );

With React Router, you’ll also need to explicity render the exported routes in a startup function:

  1. import { Meteor } from 'meteor/meteor';
  2. import { render } from 'react-dom';
  3. import { renderRoutes } from '../imports/startup/client/routes.js';
  4. Meteor.startup(() => {
  5. render(renderRoutes(), document.getElementById('app'));
  6. });

When using React Router in Meteor, you can follow roughly the same principles as when using Flow Router, but you should also consider the idioms outlined in React Router’s own documentation.

These include some notable differences like:

  • React Router encourages you to couple your URL design and layout hierarchy in the route definition. Flow Router is more flexible, although it can involve much more boilerplate as a result.
  • React Router embraces React-specific functionality like the use of context, although you can also explicitly pass your FlowRouter instance around in context if you’d like (in fact this is probably the best thing to do).

Meteor and React

Using React in Atmosphere Packages

If you are writing an Atmosphere package and want to depend on React or an npm package that itself depends on React, you can’t use Npm.depends() and Npm.require(), as this will result in 2 copies of React being installed into the application (and besides Npm.require() only works on the server).

Instead, you need to ask your users to install the correct npm packages in the application itself. This will ensure that only one copy of React is shipped to the client and there are no version conflicts.

In order to check that a user has installed the correct versions of npm packages, you can use the tmeasday:check-npm-versions package to check dependency versions at runtime.