how to use if in jsx code example
Example 1: jsx if block
render () {
return (
<div>
{(() => {
if (someCase) {
return (
<div>someCase</div>
)
} else if (otherCase) {
return (
<div>otherCase</div>
)
} else {
return (
<div>catch all</div>
)
}
})()}
</div>
)
}
Example 2: how to use if else inside jsx in react
renderElement(){
if(this.state.value == 'news')
return <Text>data</Text>;
return null;
}
render() {
return (
<View style={styles.container}>
{ this.renderElement() }
</View>
)
}
Example 3: adding a if stement in jsx
render() {
return (
<View style={styles.container}>
{this.state.value == 'news'? <Text>data</Text>: null }
</View>
)
}
Example 4: make a if in jsx
var loginButton;
if (loggedIn) {
loginButton = <LogoutButton />;
} else {
loginButton = <LoginButton />;
}
return (
<nav>
<Home />
{loginButton}
</nav>
);
Example 5: conditional rendering react
import React, { Component } from 'react';
export class HeroComponent extends Component
{
render() {
return (
<section className={"hero" + (this.props.type ? " " + this.props.type + " " : " ") + this.props.size}>
<div className="hero-body">
<div className={"container" + this.props.alignment ? " " + this.props.alignment : ""}>
<h1 className="title">{this.props.heading}</h1>
{this.props.subheading && <h2 className="subtitle">{this.props.subheading}</h2>}
</div>
</div>
</section>
)
}
}