React Nativeでカスタムフォントを使う方法
久しぶりに記事を書いていこうと思います!
Expo製のReact NativeでGoogleフォント等を利用する時の手順をまとめます。ざっとググってみたところあまり該当の記事が見当たらなかったのでもしかしたら誰かの役に立てるかと…!
※参考 Expo: Using Custom Fonts より
"dependencies": {
"@expo-google-fonts/roboto": "^0.1.0",
"expo": "~38.0.8",
"expo-font": "~8.2.1",
"expo-status-bar": "^1.0.2",
"react": "~16.11.0",
"react-dom": "~16.11.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-38.0.2.tar.gz",
"react-native-web": "~0.11.7"
}
"devDependencies": {
"@babel/core": "^7.8.6",
"babel-preset-expo": "~8.1.0"
}
まずは ExpoのGithubを確認し、対応しているGoogleフォントを探す。
expo-font
と@expo-google-fonts/利用したいフォント
をインストールする。
(Here are a few examples of the 3020 variants of 991 fonts available:とサイトにもあるように、フォント数は991種類でしょうか。)
上記のGithub内にあるこちらのサイトでフォント名を直接入力して探してみるのも良いかもしれません。
希望のフォントが見つかったら下記の通りインストール。今回はRobotoをインストールするとします。
$ expo install expo-font @expo-google-fonts/roboto
完了したらベースとなるコンポーネント(今回はApp.js)にてimportします。
import React from 'react';
// 必要なGoogleフォントをinstallする
import {
useFonts,
Roboto_400Regular,
Roboto_700Bold,
} from '@expo-google-fonts/roboto';
import { AppLoading } from 'expo';
import Home from './screens/Home';
export default function App() {
// フォントを設定
let [fontsLoaded] = useFonts({
Roboto_400Regular,
Roboto_700Bold,
});
if (!fontsLoaded) {
return <AppLoading />;
}
return <Home />;
}
Appに対しての子コンポーネントであるHome.jsでもフォントを使用可能
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
const Home = () => {
return (
<View style={styles.container}>
<Text style={styles.titleText}>helloo</Text>
</View>
);
};
export default Home;
const styles = StyleSheet.create({
container: {
padding: 24,
},
titleText: {
// 下記のようにfontFamilyを指定する
fontFamily: 'Roboto_400Regular',
fontSize: 20,
},
});
追記(2020/09/04)
上記のようにそれぞれのコンポーネントで逐一fontFamilyを指定するのは面倒です。。。そんな場合は、下記のようにグローバルなスタイルシートを作成してフォントを指定してください!
// styles/globalStyles.js
import { StyleSheet } from 'react-native';
export const globalStyles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
titleText: {
fontFamily: 'Roboto_400Regular',
fontSize: 18,
color: '#212121',
},
});
globalStylesをexportし、どのページからimportできるようにしましょう。そうすると新たにAboutコンポーネントを作成した際も下記のように指定可能です。
import React from 'react';
import { Text, View } from 'react-native';
// globalStyles
import { globalStyles } from '../styles/global';
const About = () => {
return (
<View style={globalStyles.container}>
<Text style={globalStyles.titleText}>About</Text>
</View>
);
};
export default About;
以上です!!
参考になりましたら嬉しいです😎