native-recipe
@lynstack/native-recipe maps a component’s props to its React Native
styles. You write the styles of each prop value once, in a
recipe, and call it with the
props to get the style.
import { createStyleRecipe } from "@lynstack/native-recipe";
export const badge = createStyleRecipe({ base: { alignSelf: "flex-start", borderRadius: 999, paddingHorizontal: 8 }, variants: { tone: { neutral: { backgroundColor: "#f3f4f6" }, danger: { backgroundColor: "#fee2e2" }, }, size: { sm: { height: 20 }, md: { height: 24 } }, }, defaultVariants: { size: "md" },});badge({ tone: "danger" }) === badge({ tone: "danger" }); // => trueWhich function to use
Section titled “Which function to use”| You want to style | Use |
|---|---|
| One element, such as a badge | createStyleRecipe |
| Several elements, such as a button and its label | createSlotStyleRecipe |
| Elements whose styles come from theme tokens | createThemedRecipes, which returns both creators |
What it gives you
Section titled “What it gives you”- Stable styles. A recipe builds the style of each selection once and
returns the same frozen object for it. The
styleprop keeps its identity between renders, so React skips comparing it and a memoized child skips rendering (see How it works). - Type-safe. Every style is checked against the styles of React
Native, as in
StyleSheet.create. The result keeps the types of the properties the config declares, so a text style passed to aViewis a type error. Variant names, options, and slots are inferred from the config, and a variant without a default is required. - Themes. Build styles from the tokens of a design system, and switch between light and dark, or any theme, without writing each theme’s styles in every recipe (see Theming with design tokens).
- Fast. A call with the cache is a lookup, about 5 times as fast as merging the styles again (see Benchmarks).
- Small. ES modules only, with no code from React Native at runtime. It needs no provider, Babel plugin, or native module.
Try it
Section titled “Try it”Open the example in Expo Snack
to edit a badge and a button in the browser. The Snack runs as JavaScript (see FAQ).
When to use it
Section titled “When to use it”Use it to style React Native components whose styles depend on their
props, their state, or a theme. Keep styles that never change in
StyleSheet.create (see
Why native-recipe). To style
components on the web with class names, use
@lynstack/class-recipe.
Next steps
Section titled “Next steps”- Why native-recipe compares
it with
StyleSheet.createand theme objects. - Quick start styles a badge, a button, and a card, and types their props.
- Theming with design tokens builds a light and a dark theme with a theme provider.
- Open in Snack runs the example in the browser, without installing anything.