Chih-Chao Lam Chih-Chao Lam - 1 month ago 7
React JSX Question

Can I make a React component re-render itself when it's attribute is a reactive data source from Meteor?

e.g. I have a user profile name component:

Name = React.createClass({
render() {
let name = this.props.user ? this.props.user.profile.name : '';
return <span>{name}</span>;
}
})


How can I get the following name tag update itself automatically when user signs in/signs out:

<Name user={Meteor.user()} />

Answer

One approach to this is to use the React mixin, ReactMeteorData. In getMeteorData, make Meteor user's identity a reactive data source.

Name = React.createClass({
    mixins: [ReactMeteorData],
    getMeteorData() {
        return {
            user: Meteor.user()
        };
    },
    render() {
        return <div>{ this.data.user ? this.data.user.username : '' }</div>;
    }
});

If the user identity is meant to be passed via React properties, move the reactive data source to the containing component.

Name = React.createClass({
    render() {
        return <div>{ this.props.user ? this.props.user.username : '' }</div>;
    }
});

Parent= React.createClass({
    mixins: [ReactMeteorData],
    getMeteorData() {
        return {
            user: Meteor.user() // Or any reactive data here
        };
    },
    render() {
        return <Name user={ this.data.user } />;
    }
});

Component's render function is not reactive according to the documentation. ReactMeteorData mixin is the easiest addition to achieve reactivity.

If you access a Meteor reactive data source from your component's render method, the component will not automatically rerender when data changes. If you want your component to rerender with the most up-to-date data, access all reactive functions from inside the getMeteorData method.

Comments