Mjuice Mjuice - 5 months ago 29
Javascript Question

The if statement inside the return statement of my presentational component is throwing an unexpected token error

I have a presentational component called Navbar.jsx that returns another presentational component based on whether the user is authenticated or not. When I run webpack, I am getting an error saying that the "if" in my if statement is an unexpected token. You'll see the if else statement in the navbar-collapse div. Here is Navbar.jsx:

import React, {PropTypes} from 'react';
import PreAuthNavTabs from './PreAuthNavTabs';
import PostAuthNavTabs from './PostAuthNavTabs';

const Navbar = ({ activeUser, loginUser }) => {

return (
<div>
<div className="navbar navbar-default navbar-fixed-top" role="navigation">
<div className="container">
<div className="navbar-header">
<button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span className="sr-only">Toggle Navigaton</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<Link to="/inventory"><img className="navbar-brand" src='../../css/hello_bacsi.png'></img></Link>
</div>
<div className="navbar-collapse collapse">
{
if (activeUser) {
return <PostAuthNavTabs activeUser={activeUser} />;
} else {
return <PreAuthNavTabs loginUser={loginUser} />;
}
}
</div>
</div>
</div>
</div>
);

};

Navbar.propTypes = {
activeUser: PropTypes.object,
loginUser: PropTypes.func
};

export default Navbar;

Answer

You can't use if-else statements in JSX. Have a look at the relevant docs.


Instead, use the ternary operator:

<div className="navbar-collapse collapse">
     {activeUser ?
         <PostAuthNavTabs activeUser={activeUser} /> :
         <PreAuthNavTabs loginUser={loginUser} />
     }
</div>
Comments