ReactNative에선 JSX 내부에서 if 문을 쓸 수 있다니

nara_lee·2025년 3월 6일
0

컴포넌트

JS conditional statement

if 조건문

Ternary operator 밖에 못쓰는 React와 달리 ...

ReactNative 에서는 JSX 내부에서 if statement를 사용할 수 있다. 단 if statement를 즉시실행함수 형태로 작성해야 한다. 예시:

<Text>
  {(() => {
    if (name === "AAA") return "My name is AAA";
    else if (name === "BBB") return "My name is BBB";
    else return "My name is ReactNative";
  })()}
</Text>

React 에서 && 나 || 로 조건부 렌더링 하기

'&& 에서는 모두 true일때 가장 오른쪽 값을 반환한다.'
'&& 에서는 가장 왼쪽의 falsy 값을 반환한다.'
'|| 에서는 가장 왼쪽의 truthy 값을 반환한다.'
...

공식문서에 나와 있는 내용인데 외우기보다 Short-Circuit Evaluation 으로 이해하면 편하다.

const bool1 = true;
return bool1 && <div>내용</div>;

"내용"이 나타난다

const bool1 = true;
return bool1 || <div>내용</div>;

아무것도 나타나지 않는다. (left-hand-side 가 true 면 short-circuit 했을 때 right-hand-side까지 evalutate할 필요가 없으므로 <div>...</div>를 렌더링 하지 않음.

null and undefined

  • returning null
  • returning undefined
import { StatusBar } from "expo-status-bar";
import React, { useState } from "react";
import { StyleSheet, Text, View, Button, Pressable } from "react-native";

const App = () => {
  console.log("Expo DevTools Log Test");
  const name = "NARA";
  const [timesPressed, setTimesPressed] = useState(0);

  let textLog = "";
  if (timesPressed > 1) {
    textLog = timesPressed + "x onPress";
  } else if (timesPressed > 0) {
    textLog = "onPress";
  } else {
    textLog = "⬆︎⬆︎⬆︎";
  }

  return (
    <View style={styles.container}>
      <Text>{name}는 뚠뚠 오늘도 열씨미 개발하네</Text>
      <Text style={styles.text}>🐜 🐜 🐜</Text>
      <Text>
        {(() => {
          if (name === "AAA") return "My name is AAA";
          else if (name === "BBB") return "My name is BBB";
          else return "My name is ReactNative";
        })()}
      </Text>
      <Button
        title="Button"
        onPress={() => alert("Click !!!")}
        color="#f194ff"
      />
      <Pressable
        onPress={() => {
          setTimesPressed((current) => current + 1);
        }}
        style={({ pressed }) => [
          {
            backgroundColor: pressed ? "rgb(210, 230, 255)" : "white",
          },
          styles.wrapperCustom,
        ]}
      >
        {({ pressed }) => (
          <Text style={styles.text}>{pressed ? "Pressed!" : "Press Me"}</Text>
        )}
      </Pressable>
      <View style={styles.logBox}>
        <Text testID="pressable_press_console">{textLog}</Text>
      </View>

      <StatusBar style="auto" />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  text: {
    fontSize: 30,
  },
  logBox: {
    padding: 20,
    margin: 10,
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: "#f0f0f0",
    backgroundColor: "#f9f9f9",
  },
});
export default App;

본 후기는 [한글과컴퓨터x한국생산성본부x스나이퍼팩토리] 한컴 AI 아카데미 (B-log) 리뷰로 작성 되었습니다.

#한컴AI아카데미 #AI개발자 #AI개발자교육 #한글과컴퓨터 #한국생산성본부 #스나이퍼팩토리 #부트캠프 #AI전문가양성 #개발자교육 #개발자취업

0개의 댓글