【React Native】 The title prop of a Button must be a string
エラーの説明
Button.js コンポーネントを自作して app.js で使おうとすると、こんなエラーが帰ってきた。
Invariant Violation: The title prop of a Button must be a string
"Button の title プロップは string 型でなければならない " と言われている。
Button.js のコードはこんな感じ
export default function Button({ label }) {
return (
<View style={styles.buttonContainer}>
<Pressable
style={styles.button}
onPress={() => alert('You pressed a button.')}
>
<Text style={styles.buttonLabel}>{label}</Text>
</Pressable>
</View>
);
}
app.js のコードはこんな感じ
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, View, Button } from 'react-native';
import ImageViewer from './components/ImageViewer';
export default function App() {
return (
<View style={styles.container}>
<View style={styles.imageContainer}>
<ImageViewer placeholderImageSource={PlaceholderImage} />
</View>
<View style={styles.footerContainer}>
<Button label={'Choose a photo'} />
<Button label={'Use this photo'} />
</View>
<StatusBar style="auto" />
</View>
);
}
エラー文は title のプロップについて言及しているが、そもそも今回作成した Button コンポーネントに title のプロップは存在しない。
原因
結論として、インポート元を間違えていたことが原因だった。
app.js のインポート文を抜粋すると
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, View, Button } from 'react-native';
import ImageViewer from './components/ImageViewer';
2 行目を見てみると、自分で作った Button コンポーネントではなく react-native のパッケージ内の Button コンポーネントをインポートしてしまっていた。
react-native 側の Button コンポーネントには title プロップがあるようだ。
React Native Docs - Button
以下のように修正すると、エラーが消え正常に動作した。
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, View } from 'react-native';
import ImageViewer from './components/ImageViewer';
import Button from './components/Button';
こんなミスを起こしてしまった原因を考える。
VSCode には JavaScript (ES6) code snippets という拡張機能があり、それを使うと react-native などのパッケージにあるコンポーネントの名前を入力すると、予測変換で自動的にインポートしてくれる。
そして、自分で作ったコンポーネントと react-native パッケージ内のコンポーネントの名前が被ってしまい、予測変換機能によるインポートミスを起こしてしまった。
つまり、そもそも react や react-native などの汎用的なパッケージに含まれているコンポーネントと同じ名前の自作コンポーネントは作らないほうがいいと思われる。
Discussion