Is there a way to import blaze helpers for both Blaze & React?

We’re currently doing a refactor project and are upgrading from Blaze to React. Now we have lots of template helpers of course and we’d love to have a unified way to import the Blaze and React helpers. Is there a way how we can use the same NPM package to import helpers into a blaze view or react components/view?

i recommend to follow the container component pattern for react.

In a nutshell: components are only dependent on their properties, they don’t know how to fetch data (from collections, methods, or whatever). Containers on the other hand, know how to load data.

So your helpers belong into a container.

Imaging you have the following blaze template:


<template name="home">
   {{>PostList topic="react-to-blaze"}}
</template>

<template name="PostList">
{{#each posts}}
   {{>PostListItem}}
{{/each}}
</template>


// helpers
Template.PostList.onCreated(function() {
   this.subscribe("posts.byTopic", this.data.topic);
});

Template.PostList.helpers({
   posts() {
       return PostsCollection.find({ topic: this.topic }});
   }
});

You would then migrate the helper code to a container:

import { createContainer } from 'meteor/react-meteor-data';
import PostList from '../components/PostList.jsx';

export default PostListContainer = createContainer(({ topic }) => {
 const handle = Meteor.subscribe('posts.byTopic', topic);
 const loaded = handle.ready();
 const posts = Posts.find({topic}).fetch();
  return {
    loaded,
    posts
  };
}, PostList);

now, the subscription and posts.find part are the things you might want to share with a blaze-template. Maybe put them in a function in the same file:

import { createContainer } from 'meteor/react-meteor-data';
import PostList from '../components/PostList.jsx';

export const subscribe = ({topic}) => Meteor.subscribe("posts.byTopic", topic);

export const findData = ({topic}) => Posts.find({topic});

export default PostListContainer = createContainer((props) => {
 const handle = subscribe(props);
 const loaded = handle.ready();
 const posts = findData(props).fetch();
  return {
    loaded,
    posts
  };
}, PostList);

(notice that you have to use “fetch” on the cursor in the container, because find only returns a cursor, not an array.)

and in your helpers you can import these functions:

import {subscribe, findData} from '../containers/PostList';
// helpers
Template.PostList.onCreated(function() {
  this.subscriptionHandle = subscribe({topic: this.data.topic});
});

Template.PostList.helpers({
   posts() {
       return findData({topic: this.topic});
   }
});

I never did such a migration, but that’s how i would tackle this. I haven’t used blaze for a while, so maybe i got something wrong, but i hope you get the idea!