Conditional Rendering in React

  1. if/else
import React, { Component } from 'react'class UserGreeting extends Component {
constructor(props) {
super(props)

this.state = {
isLoggedIn: false
}
}
render() {
if (this.state.isLoggedIn) {
return ( <div> Welcome Soner </div>) } else { return ( <div> Welcome Guest </div> ) } }}export default UserGreeting
import React, { Component } from 'react'class UserGreeting extends Component {     constructor(props) { 
super(props)

this.state = {
isLoggedIn: false
}
}
render() {
let message
if (this.state.isLoggedIn) {
message = <div> Welcome Soner</div>
} else {
message = <div> Welcome Guest </div>
}
return <div> {message}</div>
} }export default UserGreeting
import React, { Component } from 'react'class UserGreeting extends Component { 
constructor(props) {
super(props)
this.state =
isLoggedIn: false
} } render() { return (
this.state.isLoggedIn ?
<div> Welcome Soner</div> :
<div> Welcome Guest</div>
)
}}
import React, { Component } from 'react'class UserGreeting extends Component {     constructor(props) {       super(props)
this.state = {
isLoggedIn: false
}} render() {
return this.state.isLoggedIn && <div> Welcome Soner</div>
}
}

Higher Order Components

Preventing Component from Rendering

function WarningBanner(props) {
if (!props.warn) { return null; }
return (
<div className="warning">
Warning!
</div>
);
}

class Page extends React.Component {
constructor(props) {
super(props);
this.state = {showWarning: true};
this.handleToggleClick = this.handleToggleClick.bind(this);
}

handleToggleClick() {
this.setState(state => ({
showWarning: !state.showWarning
}));
}

render() {
return (
<div>
<WarningBanner warn={this.state.showWarning} /> <button onClick={this.handleToggleClick}>
{this.state.showWarning ? 'Hide' : 'Show'}
</button>
</div>
);
}
}

ReactDOM.render(
<Page />,
document.getElementById('root')
);

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Soner Mezgitci

Soner Mezgitci

Software Engineer | Ruby on Rails | JavaScript | HTML5 | CSS | PostgreSQL | React | Redux