ReactNative基礎中の基礎をキャッチアップして動かすまで
概要
今回はReact Native の基礎中の基礎を学びながら、ひとまず何か動かすところまでを試してみたいと思います。
👆をベースにキャッチアップしていきたいと思います。
コアコンポーネントとネイティブコンポーネント
-
ネイティブ コンポーネント
- Android および iOS と同じビューに基づいたコンポーネント
- カスタムして作ることも可能
- 例えば
<View>
は Androidだと<ViewGroup>
iOSだと<UIView>
になる
Expoに関して
Expoは、React Nativeの機能を最大限に活かしながらも、環境構築や実機テスト、アップデートといった煩雑な作業を大幅に簡略化してくれるプラットフォームです
開発環境設定
プロジェクトを作成するには Node.js をインストールしておく必要があります。システム要件にLTSとあるので、LTSのバージョンを使います。今回は Volta を使用してNode.jsを使っていきます。
# 最新のLTSのバージョンをイストール
$ volta list node
$ volta list node
⚡️ Node runtimes in your toolchain:
v20.18.0
v22.14.0 (default) # 現時点でv22.14.0がインストールされた
早速プロジェクト作成していきます。今回は template に blank-typescript を指定し react-native-example
という名前でプロジェクトを作成しました。
$ npx create-expo-app@latest --template blank-typescript
Creating an Expo project using the blank-typescript template.
✔ What is your app named? … react-native-example
✔ Downloaded and extracted project files.
> npm install
...
✅ Your project is ready!
To run your project, navigate to the directory and run one of the following npm commands.
- cd react-native-example
- npm run android
- npm run ios
- npm run web
これでプロジェクトが作成されました。
Androidエミュレータで起動してみる
まずは👇を参考に ANDROID_HOME
等の環境変数と、Androidエミュレータの設定を行なっておきます。
準備ができたら、早速起動してみます。
$ cd eact-native-example
$ npm run start
...
› Metro waiting on exp://192.168.1.37:8081
› Scan the QR code above with Expo Go (Android) or the Camera app (iOS)
› Using Expo Go
› Press s │ switch to development build
› Press a │ open Android
› Press i │ open iOS simulator
› Press w │ open web
› Press j │ open debugger
› Press r │ reload app
› Press m │ toggle menu
› shift+m │ more tools
› Press o │ open project code in your editor
› Press ? │ show all commands
Logs for your project will appear below. Press Ctrl+C to exit.
正常に起動したらQRコードと、メニューキーが表示されるので a
を押してAndroidエミュレータを起動します。初回時は Expo Go
アプリがインストールされ App.tsx
の内容が表示されればOKです。
また、複数のAndroidエミュレータから起動するデバイスを選択するには Shift + a
で選択する事ができます。
iOSシュミレータで起動してみる
👇こちらを参考に Xcode
と Command Line Tools
をインストールし、シュミレータをインストールしておく。
早速起動し、今度は i
を入力してiOSシュミレータを起動します。
$ cd eact-native-example
$ npm run start
...
› Metro waiting on exp://192.168.1.37:8081
› Scan the QR code above with Expo Go (Android) or the Camera app (iOS)
› Using Expo Go
› Press s │ switch to development build
› Press a │ open Android
› Press i │ open iOS simulator
› Press w │ open web
› Press j │ open debugger
› Press r │ reload app
› Press m │ toggle menu
› shift+m │ more tools
› Press o │ open project code in your editor
› Press ? │ show all commands
Logs for your project will appear below. Press Ctrl+C to exit.
こちらもAndroidエミュレータ同様 Shift + i
で複数iOSシュミレータから起動するデバイスを選択できます。
簡単なサンプル実装
簡単なサンプルでAPIからユーザー一覧を取得し、一覧で表示するまで実装してみたいと思います。まずはシンプルなTextのみの一覧表示を実装してみます。
App.tsx
を以下に修正します。
import { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
type User = {
id: number;
name: string;
username: string;
email: string;
};
export default function App() {
const [isLoading, setIsLoading] = useState(true);
const [users, setUsers] = useState<User[]>([]);
const fetchUsers = async () => {
try {
const response = await fetch(
'https://jsonplaceholder.typicode.com/users'
);
const json = await response.json();
setUsers(json);
setIsLoading(false);
} catch (error) {
console.error(error);
setIsLoading(false);
}
};
useEffect(() => {
fetchUsers();
}, []);
return (
<View style={{ padding: 20 }}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
data={users}
keyExtractor={({ id }) => String(id)}
renderItem={({ item }) => (
<Text>
{item.id}, {item.name}, {item.username}, {item.email}
</Text>
)}
/>
)}
</View>
);
}
やっている事としては初回のレンダリング時に useEffect
内で fetchUsers
でユーザー一覧を取得し、取得されたデータを FlatList
というComponentで表示させています。
👇実行結果がこちら
バッドノウハウ
Androidエミュレータで実行時に以下エラーが出る。
「Failed to resolve the Android SDK path. Default install location not found: /Users/xxxxxx/Library/Android/sdk. Use ANDROID_HOME to set the Android SDK location.」
以下の環境変数が正しく設定されているか確認する
export ANDROID_HOME=${HOME}/Android/Sdk # 自身の環境に応じて設定
export PATH=${ANDROID_HOME}/tools:${PATH}
export PATH=${ANDROID_HOME}/emulator:${PATH}
export PATH=${ANDROID_HOME}/platform-tools:${PATH}
Discussion