The Ternary operator is a great way to do some conditional rendering with React!. it is a simplified conditional operator like if / else.
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'
)
);
In the above output, you can see that on clicking the Login button the message and button get’s changed and vice versa.