reactjsmeteormeteor-accountsmeteor-1.4

Meteor + React: Show different Navigation items depending on the login state


I have a Meteor + React Application where I have a Header class like this:

import React, { Component } from 'react'

import { NavLoggedIn } from './header/NavLoggedIn'
import { NavLoggedOut } from './header/NavLoggedOut'

export class Header extends Component {
    render() {
        return (
            <header className="main-header">
                <nav className="navbar navbar-static-top" role="navigation">
                    <div className="navbar-custom-menu">
                        <NavLoggedIn />
                        <NavLoggedOut />
                    </div>
                </nav>
            </header>
        )
    }
}

I've got an accounts system that works nicely but now I want to change the appearance of the NavBar based off of whether or not the user is logged in.

How could I accomplish this?

I.E.

If the Meteor user is logged in show the <NavLoggedIn /> component. Otherwise, show the <NavLoggedOut /> component.


Solution

  • You need to import { Meteor } from 'meteor/meteor' and add the following to your render() function:

    import React, { Component } from 'react'
    import { Meteor } from 'meteor/meteor
    
    import { NavLoggedIn } from './header/NavLoggedIn'
    import { NavLoggedOut } from './header/NavLoggedOut'
    
    export class Header extends Component {
        render() {
           let navigate;
            // If Meteor.userID() is null then render <NavLoggedOut />, otherwise <NavLoggedIn />
            if(Meteor.userId())
              navigate=<NavLoggedIn />;
            else
              navigate=<NavLoggedOut />
            return (
                <header className="main-header">
                    <nav className="navbar navbar-static-top" role="navigation">
                        <div className="navbar-custom-menu">
                            {navigate}
                        </div>
                    </nav>
                </header>
            )
        }
    }