0

Just started out learning React.js and I'm trying to build a resusable header that can be in two states; The user logged in || the user NOT logged in.

// Header.js
var Header = React.createClass({

    renderLoggedIn: function() {
        return (
            <div>      
                <a href="index.html">Main</a>
                <a href="user.html">User profile</a>
                <hr/>
            </div>
        );
    }, 
    renderNormal: function() {
        return (
            <div>      
                <a href="index.html">Main</a>
                <a href="login.html">Login</a>
                <hr/>
            </div>
        );
    },
    render: function() {

        if (this.props.type == "normal") {
            return this.renderNormal(); 
        }
        else {
            return this.renderLoggedIn(); 
        }
    }
});

React.render(<Header type="normal" />, document.getElementById('header'))

In the main html file (index.html), I add the header with:

// Index.html
<header id="header"></header>
<script src="src/header.js" type="text/jsx"></script>

I have another file called functions.js, where a isUserLoggedIn() function exists. The return from this function determine whether the user is logged in or not, which should reflect in the header.

// functions.js
function isUserLoggedIn() {
     return // true or false; 
}

Where do I put this logic? Can/should I call the isUserLoggedIn() functions from the React template file? If so, how?

1 Answer 1

1

To answer your question the logged in state can be passed as property.

// Header.js
var Header = React.createClass({       

    renderLoggedIn: function() {
        return (
            <div>      
                <a href="index.html">Main</a>
                <a href="user.html">User profile</a>
                <hr/>
            </div>
        );
    }, 
    renderNormal: function() {
        return (
            <div>      
                <a href="index.html">Main</a>
                <a href="login.html">Login</a>
                <hr/>
            </div>
        );
    },
    render: function() {

        if (this.props.isLoggedIn) {
            return this.renderNormal(); 
        }
        else {
            return this.renderLoggedIn(); 
        }
    }
});


React.render(<Header isLoggedIn ={isUserLoggedIn()}/>, document.getElementById('header'))

Properties are immutable so always passed down. Consider using Flux/Reflux for more complex implementations.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Is it possible to pass properties straight from the main document, in here somewhere: <script src="src/header.js" type="text/jsx"></script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.