Yanick Rochon
Yanick Rochon

Reputation: 53536

Show username in Meteor React component

One of my React component is my main layout, where I display a nav bar with the currently logged-in user. The problem is that Meteor.user() is undefined when the Component is first rendered. How would I go and properly render my nav bar once the user object has been loaded/published?

MainLayout.jsx

import React, { Component } from 'react';

export default class MainLayout extends Component {
  render() {
    return (<div>{ Meteor.user().username }</div>);
  }
}

Thanks.

Upvotes: 0

Views: 590

Answers (2)

Pankaj Jatav
Pankaj Jatav

Reputation: 2184

To use data from a Meteor collection inside a React component, we can use an Atmosphere package react-meteor-data which allows us to create a "data container" to feed Meteor's reactive data into React's component hierarchy.

meteor add react-meteor-data

import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';

class MainLayout extends Component {
  render() {
    return (<div>{ this.props.user.username }</div>);
  }
}

export default MainLayoutContainer createContainer(() => {
  return {
    user: Meteor.user()
  };
}, MainLayout);

Upvotes: 1

vijayst
vijayst

Reputation: 21846

Meteor.user() should be part of container component. react-meteor-data package should be added to the project.

import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import MainLayout from './mainLayout';

export default MainLayoutContainer = createContainer(({ params }) => {
  return {
    user: Meteor.user(),
  };
}, MainLayout);

The user will be available as props in the MainLayout component.

Upvotes: 3

Related Questions