LoginSignup
2
0

More than 3 years have passed since last update.

React render内の条件分岐

Posted at

Reactでのrender内での出し分けをする条件分岐の書き方を学んだのでメモ。

三項演算子

const testBooloean = true;

{testBooloean ? <div>testBooloean === true;</div> : <div>testBooloean === false;</div>}

やってみた
スクリーンショット 2020-03-15 1.28.16.png

&& の書き方

const testBooloean = true;

 {testBooloean && <div>testBooloean === true; </div>}

やってみた
スクリーンショット 2020-03-15 1.31.42.png

このとき注意すること!
比較する値(今回でいうtestBooloean)には必ずBooleanの値が入るようにしなきゃいけないです。

例えば...

const arr = [];

 {arr.length && <div>test</div>}

結果
スクリーンショット 2020-03-15 2.11.00.png

arr = [];なのになぜか「0」が表示されてしまいます。

arrの配列の中が空の場合...という条件にしたい場合は

const arr = [];

// Booleanになるようにしましょう
 {!!arr.length && <div>test</div>};

結果
スクリーンショット 2020-03-15 2.14.44.png

2
0
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
2
0