Basic Example

Basic Example


    function Greeting(props) {
        const isLoggedIn = props.isLoggedIn;
        if (isLoggedIn) { return <UserGreeting />; }
        return <GuestGreeting />;
    }

    ReactDOM.render(
        <Greeting isLoggedIn={false} />, document.getElementById('root')
    );
        

Stateful Component


    class LoginControl extends React.Component {
        constructor(props) {
            super(props); this.handleLoginClick = this.handleLoginClick.bind(this); this.handleLogoutClick = this.handleLogoutClick.bind(this); this.state = {isLoggedIn: false};
        }

        handleLoginClick() { this.setState({isLoggedIn: true}); }

        handleLogoutClick() { this.setState({isLoggedIn: false}); }

        render() {
            const isLoggedIn = this.state.isLoggedIn; let button;
            if (isLoggedIn) { button = <LogoutButton onClick={this.handleLogoutClick} />; }
            else { button = <LoginButton onClick={this.handleLoginClick} />; }
            return ( <div> <Greeting isLoggedIn={isLoggedIn} /> {button} </div> );
        }
    }

    ReactDOM.render( <LoginControl />, document.getElementById('root') );
        

&& operator


    render() { const count = 0; return ( <div> { count && <h1>Messages: {count}</h1>} </div> ); }
        

Ternary operator


    render() { const isLoggedIn = this.state.isLoggedIn; return ( <div> The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in. </div> ); }
        

Preventing component from rendering


    function WarningBanner(props) {
        if (!props.warn) { return null; }
        return ( <div className="warning"> Warning! </div> );
    }