Common Patterns
Frequently used code patterns.
asChild
prop
Most primitive components have an asChild
prop. When it is set to true
, it passes all of its props to its immediate child and renders the child instead of the primitive. To make this possible, the internal implementation of the primitive uses the Slot
primitive.
Examples
Implementation with an asChild
prop
Using the asChild
prop to conditionally render a custom Button
as a Pressable
or a Slot.Pressable
.
Use of a componnent that has an asChild
prop
Setting the asChild
prop to true
to pass all of the Button
props to the Pressable
component.
Forwarding Refs
Refs are used for Direct Manipulation. A common pratice is to set a ref to a component, then use the ref to call methods or access properties of the component.
Passing a ref to react-native
components
Passing a ref
to the TextInput
component, allows us to call the focus
method when the Pressable
is pressed.
Custom components with ref
In React, the ref
prop is a reserved prop since it needs to be handled differently. To forward a ref to a child component, you must use the React.forwardRef
function.
Creating a component that accepts a ref