A text node cannot be a child of a <View>.

임경섭·2025년 3월 10일
1

React Native를 이용해 운동 예약 앱을 만들던 도중 A text node cannot be a child of a View. 에러를 발견했다.
대충 에러 내용을 보면 View의 자식 노드로 있는 text에 문제가 있는것으로 보인다.

회원가입 페이지인데, 글자 수가 2글자 이하거나 정규식이 맞지 않을때 경고 메세지를 보여주려했다.

<View style={[styles.container, colorScheme === 'dark' && styles.darkContainer]}>
           <Text style={[styles.title, colorScheme === 'dark' && styles.darkText]}>회원가입</Text>
           <TextInput
               style={[styles.input, colorScheme === 'dark' && styles.darkInput]}
               placeholder="이름"
               value={formData.name}
               onChangeText={text => handleChange('name', text)}
           />
           <TextInput
               style={[styles.input, colorScheme === 'dark' && styles.darkInput]}
               placeholder="이메일"
               value={formData.email}
               onChangeText={text => handleChange('email', text)}
           />
           <TextInput
               style={[styles.input, colorScheme === 'dark' && styles.darkInput]}
               placeholder="비밀번호"
               value={formData.password}
               onChangeText={text => handleChange('password', text)}
               secureTextEntry
           />
           {errors.name && <Text style={styles.errorText}>{errors.name}</Text>}
           {errors.email && <Text style={styles.errorText}>{errors.email}</Text>}
           {errors.password && <Text style={styles.errorText}>{errors.password}</Text>}
           <Button title="회원가입" onPress={handleSignup} />
       </View>

하지만 해당 에러 구문에서 에러가 발생하였다.
원래 코드의 문제점은 errors.name이 빈 문자열일 경우 false를 반환하지만, JavaScript에서는 false도 하나의 값으로 인식하여 렌더링을 시도한다는 점이다. 따라서 View에서는 false값을 직접적으로 가질 수 없기 때문에 에러가 발생하는것이다.

따라서 아래와 같은 코드로 수정하였다.

{errors.name ? <Text style={styles.errorText}>{errors.name}</Text> : null}
{errors.email ? <Text style={styles.errorText}>{errors.email}</Text> : null}
{errors.password ? <Text style={styles.errorText}>{errors.password}</Text> : null}

null값일 경우 렌더링을 하지 않기 때문에, 에러가 발생하지 않는다.

profile
즐겁게 코딩 ૮₍ •̀ᴥ•́ ₎ა

1개의 댓글

comment-user-thumbnail
2025년 3월 17일

오 React Native부분도 이제는 다루시는군요!

답글 달기