ReactJS Tutorial - Conditional Rendering

jh22j9·2020년 11월 19일
0

Conditional Rendering


  1. if/else
  2. Element variables
  3. Tenary conditional operator
  4. Short circuit operator

1. if/else

import React, { Component } from 'react'

class UserGreeting extends Component {
  constructor(props) {
    super(props)
  
    this.state = {
       isLoggedIn: true
    }
  }
  render() {
      if(this.state.isLoggedIn) {
        return <div>Welcome Dukkha</div>
      } else {
        return<div>Welcome Guest</div>
      }
  }
}

export default UserGreeting

If statement don't work inside the JSX. So we have if/else statement outside the JSX and the entire return statment containing the JSX is placed inside the if or else block.

2. Element variables

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 Heeju</div>
  } else {
    message = <div>Welcome Guest</div>
  }
  return <div>{message}</div>
  }
}

export default UserGreeting

3. Tenary conditional operator

The benefit of this approach is that it can be used inside the JSX.

import React, { Component } from 'react'

class UserGreeting extends Component {
  constructor(props) {
    super(props)
  
    this.state = {
       isLoggedIn: false
    }
  }
  render() {
    return (
       this.state.isLoggedIn ?
       <div>Welcome Heeju</div> : 
       <div>Welcome Guest</div>
    )
  }
}

export default UserGreeting

4. Short circuit operator

When you want to render either something or nothing.

import React, { Component } from 'react'

class UserGreeting extends Component {
  constructor(props) {
    super(props)
  
    this.state = {
       isLoggedIn: false
    }
  }
  render() {
    return this.state.isLoggedIn && <div>Welcome Heeju</div>
  }
}

export default UserGreeting

🔗 ReactJS Tutorial - 16 - Conditional Rendering

0개의 댓글

관련 채용 정보