LoginSignup
0

More than 1 year has passed since last update.

Conditional Renderingのfalsy値の扱い

Last updated at Posted at 2023-01-11

条件部Rendering例

import React from 'react'

function UserGreeting(props) {
    return <h1>{props.name && props.name + ','} 
           welcome {props.count && `It's ${props.count} times`} </h1>
}

function GuestGreeting(props) {
    return <h1>Please sign up.</h1>
}

function Greeting(props) {
    return  props.isLoggedIn ? <UserGreeting name="jimmy" count={0} /> : <GuestGreeting />
}

export default function Condition() {
    const isLoggedIn = true;
    return (
        <div><Greeting isLoggedIn={isLoggedIn} /></div>
    )
}

&&演算子とfalsy

    return <h1>{props.name && props.name + ','} 
           welcome {props.count && `It's ${props.count} times`} </h1>

A && B : Aがtrueなら、Bを出力する。Aがfalseなら、何も出力しない。
    ここで要注意は、Aが0のようにfalsyな値の場合はAを出力してしまうので注意が必要!
    countが’0’なら、出力結果が「Welcome 0」となる。

falsy value : 0、-0、0n、""、null、undefined、NaN

falsy値による不具合を制御

falsyな値により、予想出来なかった出力結果になることを制御するために二つの方法があるかと思います。
①Booleanを囲んでfalsy値をfalse値に明確化にする
    return <h1>{props.name && props.name + ','} 
           welcome {Boolean(props.count) && `It's ${props.count} times`} </h1>

②3項演算子を使用する

    return <h1>{props.name && props.name + ','} 
           welcome {props.count ? `It's ${props.count} times` : null} </h1>

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
0