React Tutorial

React Home React Intro React Get Started React ES6 - ES6 Classes - ES6 Arrow Functions - ES6 Variables - ES6 Array Methods - ES6 Destucturing - ES6 Spread Operator - ES6 Modules - ES6 Ternary Operator React Render HTML React JSX React Components React Class React Props React Events React Conditionals React Lists React Forms React Router React Memo React CSS Styling

React Hooks

What is a Hook? useState useEffect useContext useRef useReducer useCallback useMemo Custom Hooks

React Redux

What is a Redux? React Redux Example

React Exercises

React Quiz

React ES6 Ternary Operator

The Ternary operator is a great way to do some conditional rendering with React!. it is a simplified conditional operator like if / else.

Syntax :

condition ? expr_if_true : expr_if_false

{
condition ? ("condition is true") : ("condition is false")
}

When the condition is true, it returns “condition is true” otherwise it returns “condition is false“.

import React from 'react';
import ReactDOM from 'react-dom';
 
// Message Component
function Message(props)
{
    if (props.isLoggedIn)
        return <h1>Welcome User</h1>;
    else
        return <h1>Please Login</h1>;
}
 
// Login Component
function Login(props)
{
   return(
           <button onClick = {props.clickFunc}>
               Login
           </button>
       );
}
 
// Logout Component
function Logout(props)
{
    return(
           <button onClick = {props.clickFunc}>
               Logout
           </button>
       );
}
 
// Parent Homepage Component
class Homepage extends React.Component{
 
    constructor(props)
    {
        super(props);
 
        this.state = {isLoggedIn : false};
 
        this.ifLoginClicked = this.ifLoginClicked.bind(this);
        this.ifLogoutClicked = this.ifLogoutClicked.bind(this);
    }
 
    ifLoginClicked()
    {
        this.setState({isLoggedIn : true});
    }
 
    ifLogoutClicked()
    {
        this.setState({isLoggedIn : false});
    }
 
    render(){
 
        return(
 
            <div>
 
                <Message isLoggedIn = {this.state.isLoggedIn}/>
                 
                {
                    (this.state.isLoggedIn)?(
                    <Logout clickFunc = {this.ifLogoutClicked} />
                    ) : (
                    <Login clickFunc = {this.ifLoginClicked} />
                    )
                }
 
            </div>
                 
            );
    }
}
 
ReactDOM.render(
    <Homepage />,
    document.getElementById('root')
);

Output :

In the above output, you can see that on clicking the Login button the message and button get’s changed and vice versa.