conditional rendering functional component react code example
Example 1: react native conditional rendering
class Component extends React.Component {
const a = true
render() {
return (
{a == true
? ( )
: null
}
)
}
}
This is staying: if a == true, render a button component.
Otherwise render null, in other words nothing.
Example 2: ternary react
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
The user is {isLoggedIn ? 'currently' : 'not'} logged in.
);
}
Example 3: conditional props react
// single prop
propName={ condition ? something : somethingElse }
propName={ condition && something }
// multiple props
{ ...( condition ? { ...setOfProps } : { ...setOfOtherProps })}
{ ...( condition && { ...setOfProps })}
Example 4: adding a if stement in jsx
render() {
return (
{this.state.value == 'news'? data : null }
)
}
Example 5: react native conditional rendering
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
Hello!
{unreadMessages.length > 0 &&
You have {unreadMessages.length} unread messages.
}
);
}
Example 6: conditional rendering react
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
Hello!
{unreadMessages.length > 0 && You have {unreadMessages.length} unread messages. }
);
}
const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
,
document.getElementById('root')
);