how to add conditional html component react code example
Example 1: conditional style react
class App extends Component {
constructor() {
super()
this.state = { isRed: true }
}
render() {
const isRed = this.state.isRed
return <p style={{ color: isRed ? 'red' : 'blue' }}>Example Text</p>
}
}
Example 2: conditional rendering react
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 && <h2> You have {unreadMessages.length} unread messages. </h2> } </div>
);
}
const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
<Mailbox unreadMessages={messages} />,
document.getElementById('root')
);