new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Expo & React Native · all subjects

assets

40 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Static assets definition and types

A static asset is a file bundled with your app's native binary, separate from the JavaScript bundle containing your app's code. Common types include images, videos, sounds, database files for SQLite, and fonts. These assets can be served locally from your project or remotely over the network.

Import images with require statement

To render an image in your app, you can import it using a require statement. For example, to render an image called example.png from assets/images directory in App.js: <Image source={require('./assets/images/example.png')} />. The bundler automatically reads the imported image's metadata and provides width and height.

Local asset serving behavior

Locally stored assets are served over HTTP in development. For production apps, they are automatically bundled into the app binary at build time and served from disk on the device.

Load asset at build time with expo-asset config plugin

Use the config plugin from the expo-asset library to embed assets in the native project at build time. Install expo-asset with npx expo install expo-asset. Configure the plugin in app.json by adding expo-asset to plugins array with an assets property containing an array of file paths or directories relative to the project root. After configuring, create a new development build. Assets loaded this way can be imported directly without require/import statements using their resource name as URI, and must explicitly provide width and height.

expo-asset config plugin configuration example

Configuration in app.json: ```json { "expo": { "plugins": [ [ "expo-asset", { "assets": ["./assets/images/example.png"] } ] ] } } ``` The assets property takes an array of file paths or directories relative to the project root.

Use asset with expo-asset config plugin example

After embedding an asset with the config plugin and creating a development build, you can use it directly: ```tsx import { Image } from 'expo-image'; export default function HomeScreen() { return <Image source={{ uri: 'example' }} style={{ width: 100, height: 100 }} />; } ``` Note that width and height must be explicitly provided when rendering assets without using require.

Load asset at runtime with useAssets hook

The useAssets hook from expo-asset library loads assets asynchronously. It downloads and stores an asset locally, then returns a list of the asset's instances after loading. Install expo-asset with npx expo install expo-asset.

useAssets hook usage example

Import and use the useAssets hook: ```tsx import { useAssets } from 'expo-asset'; export default function HomeScreen() { const [assets, error] = useAssets([ require('path/to/example-1.jpg'), require('path/to/example-2.png'), ]); return assets ? <Image source={assets[0]} /> : null; } ```

Serve asset remotely with URL

When an asset is served remotely, it is not bundled into the app binary. You can pass the URL of the asset resource to components like <Image>. For remote assets, you must explicitly provide metadata like width and height since the bundler cannot retrieve it. Remote assets have no guarantee of availability due to potential lack of internet connection or asset removal.

Remote asset URL example

To render a remote image: ```jsx import { Image } from 'expo-image'; function App() { return ( <Image source={{ uri: 'https://example.com/logo.png' }} style={{ width: 50, height: 50 }} /> ); } ``` Width and height must be explicitly provided for remote assets.

Image optimization tools

Images can be compressed using: guetzli, pngcrush, or optipng. Lossless optimizers re-encode images to be smaller without pixel changes, suitable when each pixel must be preserved (using PNG format). Lossy optimizers discard visual information to reduce file size while maintaining visual similarity. Tools like imagemagick with SSIM comparison algorithms can demonstrate image similarity metrics.

Asset optimization for non-image formats

For assets like GIFs, videos, or non-code and non-image assets, optimization and minification is the responsibility of the developer. Note that GIFs are a very inefficient format, and modern video codecs can produce significantly smaller file sizes with better quality than GIFs.

Supported font formats across platforms

Expo SDK officially supports OTF and TTF font formats across Android, iOS, and web platforms. For other formats, advanced configuration is required.

Variable fonts platform support

Variable fonts, including variable implementations in OTF and TTF, do not have support across all platforms. For full platform support, use static fonts. Alternatively, use fontTools to extract a specific axis configuration from a variable font and save it as a separate font file.

OTF vs TTF font files

If a font is available in both OTF and TTF versions, prefer OTF. OTF files are smaller than TTF files and sometimes render slightly better in certain contexts.

Local font directory convention

The assets/fonts directory path is a common convention in React Native apps for storing font files. Fonts can be placed elsewhere if following a custom convention.

PostScript name for consistent font naming

The PostScript name of a font is a unique identifier assigned to the font following Adobe's PostScript standard. It is recommended to name font files the same as their PostScript name so the font family name is consistent between Android and iOS platforms. For example, the Inter Black font has PostScript name 'Inter-Black'.

Google Fonts support via @expo-google-fonts

Expo has first-class support for all fonts listed in Google Fonts via the @expo-google-fonts library. Individual font packages like @expo-google-fonts/inter provide access to that font and its variants.

Google Fonts package useFonts hook

Each Google Fonts package provides its own useFonts hook. The font package imports the font file automatically, so explicit import of the font file is not required. For example, with @expo-google-fonts/inter, import { Inter_900Black, useFonts } from '@expo-google-fonts/inter'.

Font formats support table across platforms

Format support matrix: bdf (none), dfont (Android only), eot (Web only), fon (none), otf (Android/iOS/Web), ps (none), svg (Web only), ttc (none), ttf (Android/iOS/Web), woff (iOS/Web), woff2 (iOS/Web).

Default platform fonts

On Android, the default font is Roboto. On iOS, the default font is SF Pro. These are used when no custom fontFamily is specified.

Remote font loading CORS requirement

When loading remote fonts, ensure they are served from an origin with CORS properly configured. Without proper CORS configuration, remote fonts may not load properly on the web platform.

useFonts with remote font URL

Remote fonts can be loaded with useFonts by passing a URL string instead of require(). Example: useFonts({ 'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12' }). Local assets are safer as they're bundled with the app and avoid CORS issues.

Beyond OTF and TTF customization

For fonts in formats other than OTF or TTF, customize the Metro bundler configuration to include them as extra assets by modifying assetExts configuration. Rendering unsupported font formats on a platform may cause app crashes.

@expo/vector-icons deprecation and migration

@expo/vector-icons is deprecated and not recommended for new projects. Users should migrate to react-native-vector-icons instead. See the Expo blog for migration details.

Ionicons example with @expo/vector-icons

The Ionicons font can be loaded from @expo/vector-icons. Example: import Ionicons from '@expo/vector-icons/Ionicons'; then use <Ionicons name="checkmark-circle" size={32} color="green" />. The font object is available as a static property: Ionicons.font evaluates to {ionicons: require('path/to/ionicons.ttf')}.

createIconSet method for custom icon fonts

The createIconSet method from @expo/vector-icons creates a custom icon set. It takes three arguments: glyphMap (object where keys are icon names and values are UTF-8 characters or character codes), fontFamily (the name of the font, not the filename), and optionally a custom font file name for Android support. Example: createIconSet({icon-name: 1234, test: '∆'}, 'fontFamily', 'custom-icon-font.ttf').

createIconSetFromIcoMoon for IcoMoon config files

The createIconSetFromIcoMoon method creates a custom font from an IcoMoon config file. Requires selection.json and .ttf files saved in the project (preferably in assets directory). The font must be loaded using useFonts hook or Font.loadAsync before using. Note: only supports the old IcoMoon app format; new app format support is pending release.

createIconSetFromIcoMoon usage example

Example of createIconSetFromIcoMoon: const Icon = createIconSetFromIcoMoon( require('./assets/icomoon/selection.json'), 'IcoMoon', 'icomoon.ttf' ); Then load the font with useFonts before rendering: const [fontsLoaded] = useFonts({ IcoMoon: require('./assets/icomoon/icomoon.ttf'), });

createIconSetFromFontello for Fontello config files

The createIconSetFromFontello method creates a custom font from a Fontello config file. Requires config.json and .ttf files saved in the project (preferably in assets directory). Must load the font using useFonts hook or Font.loadAsync before using. Example: createIconSetFromFontello(fontelloConfig, 'fontello', 'fontello.ttf').

Icon Button component from @expo/vector-icons

Icon buttons can be created using Font.Button syntax where Font is an icon set imported from @expo/vector-icons. Example: FontAwesome.Button accepts props for onPress handlers and can wrap button text. The component inherits from Text, TouchableHighlight, and TouchableWithoutFeedback.

Icon Button component props

Icon Button props include: color (text and icon color, default 'white'), size (icon size, default 20), iconStyle (styles applied to icon only, default {marginRight: 10}), backgroundColor (button background, default '#007AFF'), borderRadius (border radius, default 5, set to 0 to disable), onPress (function called when pressed, default None). Also accepts any Text, TouchableHighlight, or TouchableWithoutFeedback properties.

FontAwesome Button example

Example of creating an icon button with FontAwesome: import FontAwesome from '@expo/vector-icons/FontAwesome'; <FontAwesome.Button name="facebook" backgroundColor="#3b5998" onPress={() => console.log('Button pressed')}> Login with Facebook </FontAwesome.Button>

Icon fonts available through @expo/vector-icons

Popular icon sets available through @expo/vector-icons include FontAwesome, Glyphicons, and Ionicons. All available icons can be browsed at icons.expo.fyi.

Custom font file requirements for icon sets

When creating custom icon sets for Android support, the font file name (not the file path) must be specified. For IcoMoon and Fontello icons, the files should be saved in the assets directory for organization.

expo-image-picker installation command

To install expo-image-picker, stop the development server by pressing Ctrl+C in the terminal, then run `npx expo install expo-image-picker`, `yarn expo install expo-image-picker`, `pnpm expo install expo-image-picker`, or `bun expo install expo-image-picker` depending on your package manager. The command installs the library and adds it to package.json dependencies.

launchImageLibraryAsync method options

The ImagePicker.launchImageLibraryAsync() method accepts an ImagePickerOptions object with the following options: mediaTypes (array specifying type of media, e.g. ['images']), allowsEditing (boolean that when true allows user to crop the image on Android and iOS during selection), and quality (numeric value for image quality, e.g. 1).

launchImageLibraryAsync return value structure

launchImageLibraryAsync() returns an object with properties: assets (array containing selected image objects), and canceled (boolean indicating if user canceled the operation). Each asset object contains: assetId (string or null), base64 (null or base64 string), duration (null or number), exif (null or object), fileName (string), fileSize (number), height (number), mimeType (string like 'image/jpeg'), rotation (null or number), type (string like 'image'), uri (string file path), and width (number). On web, assets contain only fileName, height, mimeType, and uri (data URL).

Image picker example for selecting and displaying image

Example showing how to use expo-image-picker to select and display an image: ```tsx import * as ImagePicker from 'expo-image-picker'; import { useState } from 'react'; export default function Index() { const [selectedImage, setSelectedImage] = useState<string | undefined>(undefined); const pickImageAsync = async () => { let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], allowsEditing: true, quality: 1, }); if (!result.canceled) { setSelectedImage(result.assets[0].uri); } else { alert('You did not select any image.'); } }; return ( <View> <Button onPress={pickImageAsync} label="Choose a photo" /> </View> ); } ``` This example imports ImagePicker, creates a state variable for the selected image URI, defines pickImageAsync to launch the library and save the selected image URI, and calls pickImageAsync on button press.

Development server restart after installing expo-image-picker

After installing a new library like expo-image-picker, stop the development server by pressing Ctrl+C in the terminal, run the installation command, then start the development server again by running `npx expo start`.

Give your agent this brain