Help us understand the problem. What is going on with this article?

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

はじめに

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つがシンプルかなと思います。
ありがとうございました。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした