LoginSignup
9
10

More than 3 years have passed since last update.

Reactでの条件分岐 4つの方法のメモ

Last updated at Posted at 2020-01-19

はじめに

Reactでの条件付きレンダリングの方法のメモです。

目次

  1. returnするJSXを分岐
  2. 変数にJSXを格納
  3. もう少し短く!!
  4. これで最後!!
  5. まとめ

1. returnするJSXを分岐

stateを条件に、判定してJSXをそのままreturnしてあげる方式

import React, { Component } from 'react'

export default class Greeting extends Component {

    constructor(props) {
        super(props);
        this.state = {
            isMorning: true
        };
    }
    render() {
        if (this.state.isMorning) {

            return <h2> Good Morning Tom</h2>

        } else {

            return <h2> Hye ! Tom </h2>

        }

    }
}

2. 変数にJSXを格納

変数にJSXを格納することで、returnの箇所が1つになりました。

import React, { Component } from 'react'

export default class Greeting extends Component {

    constructor(props) {
        super(props);
        this.state = {
            isMorning: false
        };
    }
    render() {
        let message

        if (this.state.isMorning) {

            message = <h2> Good Morning Tom</h2>

        } else {

            message = <h2> Hye ! Tom </h2>

        }

        return <div>{message}</div>

    }
}

3. もう少し短く!!

もう少し短く書けます
条件式 ? (trueの時) : (falseの時)

import React, { Component } from 'react'

export default class Greeting extends Component {

    constructor(props) {
        super(props);
        this.state = {
            isMorning: true
        };
    }
    render() {
        return (this.state.isMorning ?<h2> Good Morning Tom</h2> :<h2> Hye ! Tom </h2>)
    }
}

4.これで最後!!

falseの時に、何も表示させない時とかは
条件式 && (trueの時)
みたいに書ける

条件式が評価されて、trueなら次に行くので
条件式がfalseなら次に行かずに何も返さない

import React, { Component } from 'react'

export default class Greeting extends Component {

    constructor(props) {
        super(props);
        this.state = {
            isMorning: true
        };
    }
    render() {
        return (this.state.isMorning && <h2> Good Morning Tom</h2>)
    }
}

5. まとめ

4つのパターンを見ましたが、最後の2つがシンプルかなと思います。
ありがとうございました。

9
10
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10