This example shows how a MongoDB collection can be displayed in a React component. The collection is continuously synchronized between server and client, and the page instantly updates as database contents change.
To connect React components and Meteor collections, you'll need the react-meteor-data
package.
$ meteor add react-meteor-data
$ meteor npm install react-addons-pure-render-mixin
A simple collection is declared in both/collections.js
. Every source file in both
directory is both client-side and server-side code:
import { Mongo } from 'meteor/mongo';
// This collection will contain a list of random numbers
export const Numbers = new Mongo.Collection("numbers");
The collection needs to be published on the server. Create a simple publication in server/publications.js
:
import { Meteor } from 'meteor/meteor';
import { Numbers } from '/both/collections.js';
// This publication synchronizes the entire 'numbers' collection with every subscriber
Meteor.publish("numbers/all", function() {
return Numbers.find();
});
Using the createComponent
function we can pass reactive values (like the Numbers
collection) to a React component. client/shownumbers.jsx
:
import React from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Numbers } from '/both/collections.js';
// This stateless React component renders its 'numbers' props as a list
function _ShowNumbers({numbers}) {
return <div>List of numbers:
<ul>
// note, that every react element created in this mapping requires
// a unique key - we're using the _id auto-generated by mongodb here
{numbers.map(x => <li key={x._id}>{x.number}</li>)}
</ul>
</div>;
}
// Creates the 'ShowNumbers' React component. Subscribes to 'numbers/all' publication,
// and passes the contents of 'Numbers' as a React property.
export const ShowNumbers = createContainer(() => {
Meteor.subscribe('numbers/all');
return {
numbers: Numbers.find().fetch(),
};
}, _ShowNumbers);
Initially the database is probably empty.
Add entries to MongoDB and watch as the page updates automatically.
$ meteor mongo
MongoDB shell version: 3.2.6
connecting to: 127.0.0.1:3001/meteor
meteor:PRIMARY> db.numbers.insert({number: 5});
WriteResult({ "nInserted" : 1 })
meteor:PRIMARY> db.numbers.insert({number: 42});
WriteResult({ "nInserted" : 1 })