TextView
- Properties
- Example
- Source Code
- Accessibility
Name | Type | Default Value | Required | Description |
---|---|---|---|---|
accessible | boolean | No | When true, indicates that the view is an accessibility element. By default, all the touchable elements are accessible. | |
accessibilityActions | readonly Readonly<{ name: string; label?: string; }>[] | No | Provides an array of custom actions available for accessibility. | |
accessibilityLabel | string | No | Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the children and accumulating all the Text nodes separated by space. | |
aria-label | string | No | Alias for accessibilityLabel https://reactnative.dev/docs/view#accessibilitylabel https://github.com/facebook/react-native/issues/34424 | |
accessibilityRole | AccessibilityRole | No | Accessibility Role tells a person using either VoiceOver on iOS or TalkBack on Android the type of element that is focused on. | |
accessibilityState | AccessibilityState | No | Accessibility State tells a person using either VoiceOver on iOS or TalkBack on Android the state of the element currently focused on. | |
aria-busy | boolean | No | alias for accessibilityState see https://reactnative.dev/docs/accessibility#accessibilitystate | |
aria-checked | boolean | "mixed" | No | ||
aria-disabled | boolean | No | ||
aria-expanded | boolean | No | ||
aria-selected | boolean | No | ||
accessibilityHint | string | No | An accessibility hint helps users understand what will happen when they perform an action on the accessibility element when that result is not obvious from the accessibility label. | |
accessibilityValue | AccessibilityValue | No | Represents the current value of a component. It can be a textual description of a component's value, or for range-based components, such as sliders and progress bars, it contains range information (minimum, current, and maximum). | |
aria-valuemax | number | No | ||
aria-valuemin | number | No | ||
aria-valuenow | number | No | ||
aria-valuetext | string | No | ||
onAccessibilityAction | (event: AccessibilityActionEvent) => void | No | When `accessible` is true, the system will try to invoke this function when the user performs an accessibility custom action. | |
importantForAccessibility | "auto" | "yes" | "no" | "no-hide-descendants" | No | [Android] Controlling if a view fires accessibility events and if it is reported to accessibility services. | |
aria-hidden | boolean | No | A value indicating whether the accessibility elements contained within this accessibility element are hidden. | |
aria-modal | boolean | No | ||
role | Role | No | Indicates to accessibility services to treat UI component like a specific role. | |
accessibilityLabelledBy | string | string[] | No | Identifies the element that labels the element it is applied to. When the assistive technology focuses on the component with this props, the text is read aloud. The value should should match the nativeID of the related element. @platform android | |
aria-labelledby | string | No | Identifies the element that labels the element it is applied to. When the assistive technology focuses on the component with this props, the text is read aloud. The value should should match the nativeID of the related element. @platform android | |
accessibilityLiveRegion | "none" | "polite" | "assertive" | No | Indicates to accessibility services whether the user should be notified when this view changes. Works for Android API >= 19 only. @platform android See https://reactnative.dev/docs/view#accessibilityliveregion | |
aria-live | "polite" | "assertive" | "off" | No | Indicates to accessibility services whether the user should be notified when this view changes. Works for Android API >= 19 only. @platform android See https://reactnative.dev/docs/view#accessibilityliveregion | |
accessibilityElementsHidden | boolean | No | A Boolean value indicating whether the accessibility elements contained within this accessibility element are hidden to the screen reader. @platform ios | |
accessibilityViewIsModal | boolean | No | A Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver. @platform ios | |
onAccessibilityEscape | () => void | No | When accessible is true, the system will invoke this function when the user performs the escape gesture (scrub with two fingers). @platform ios | |
onAccessibilityTap | () => void | No | When `accessible` is true, the system will try to invoke this function when the user performs accessibility tap gesture. @platform ios | |
onMagicTap | () => void | No | When accessible is true, the system will invoke this function when the user performs the magic tap gesture. @platform ios | |
accessibilityIgnoresInvertColors | boolean | No | https://reactnative.dev/docs/accessibility#accessibilityignoresinvertcolorsios @platform ios | |
accessibilityLanguage | string | No | By using the accessibilityLanguage property, the screen reader will understand which language to use while reading the element's label, value and hint. The provided string value must follow the BCP 47 specification (https://www.rfc-editor.org/info/bcp47). https://reactnative.dev/docs/accessibility#accessibilitylanguage-ios @platform ios | |
children | ReactNode | No | react nodes passed to the component | |
hitSlop | number | Insets | No | This defines how far a touch event can start away from the view. Typical interface guidelines recommend touch targets that are at least 30 - 40 points/density-independent pixels. If a Touchable view has a height of 20 the touchable height can be extended to 40 with hitSlop={{top: 10, bottom: 10, left: 0, right: 0}} NOTE The touch area never extends past the parent view bounds and the Z-index of sibling views always takes precedence if a touch hits two overlapping views. | |
id | string | No | Used to reference react managed views from native code. | |
needsOffscreenAlphaCompositing | boolean | No | Whether this view needs to rendered offscreen and composited with an alpha in order to preserve 100% correct colors and blending behavior. The default (false) falls back to drawing the component and its children with an alpha applied to the paint used to draw each element instead of rendering the full component offscreen and compositing it back with an alpha value. This default may be noticeable and undesired in the case where the View you are setting an opacity on has multiple overlapping elements (e.g. multiple overlapping Views, or text and a background). Rendering offscreen to preserve correct alpha behavior is extremely expensive and hard to debug for non-native developers, which is why it is not turned on by default. If you do need to enable this property for an animation, consider combining it with renderToHardwareTextureAndroid if the view contents are static (i.e. it doesn't need to be redrawn each frame). If that property is enabled, this View will be rendered off-screen once, saved in a hardware texture, and then composited onto the screen with an alpha each frame without having to switch rendering targets on the GPU. | |
onLayout | (event: LayoutChangeEvent) => void | No | Invoked on mount and layout changes with {nativeEvent: { layout: {x, y, width, height}}}. | |
pointerEvents | "none" | "box-none" | "box-only" | "auto" | No | In the absence of auto property, none is much like CSS's none value. box-none is as if you had applied the CSS class: .box-none { pointer-events: none; } .box-none * { pointer-events: all; } box-only is the equivalent of .box-only { pointer-events: all; } .box-only * { pointer-events: none; } But since pointerEvents does not affect layout/appearance, and we are already deviating from the spec by adding additional modes, we opt to not include pointerEvents on style. On some platforms, we would need to implement it as a className anyways. Using style or not is an implementation detail of the platform. | |
removeClippedSubviews | boolean | No | This is a special performance property exposed by RCTView and is useful for scrolling content when there are many subviews, most of which are offscreen. For this property to be effective, it must be applied to a view that contains many subviews that extend outside its bound. The subviews must also have overflow: hidden, as should the containing view (or one of its superviews). | |
style | StyleProp<ViewStyle> | No | ||
testID | string | No | Used to locate this view in end-to-end tests. Optional TestID | |
nativeID | string | No | Used to reference react managed views from native code. | |
collapsable | boolean | No | Views that are only used to layout their children or otherwise don't draw anything may be automatically removed from the native hierarchy as an optimization. Set this property to false to disable this optimization and ensure that this View exists in the native view hierarchy. | |
collapsableChildren | boolean | No | Setting to false prevents direct children of the view from being removed from the native view hierarchy, similar to the effect of setting `collapsable={false}` on each child. | |
renderToHardwareTextureAndroid | boolean | No | Whether this view should render itself (and all of its children) into a single hardware texture on the GPU. On Android, this is useful for animations and interactions that only modify opacity, rotation, translation, and/or scale: in those cases, the view doesn't have to be redrawn and display lists don't need to be re-executed. The texture can just be re-used and re-composited with different parameters. The downside is that this can use up limited video memory, so this prop should be set back to false at the end of the interaction/animation. | |
focusable | boolean | No | Whether this `View` should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard. | |
tabIndex | 0 | -1 | No | Indicates whether this `View` should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard. See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex for more details. Supports the following values: - 0 (View is focusable) - -1 (View is not focusable) | |
shouldRasterizeIOS | boolean | No | Whether this view should be rendered as a bitmap before compositing. On iOS, this is useful for animations and interactions that do not modify this component's dimensions nor its children; for example, when translating the position of a static view, rasterization allows the renderer to reuse a cached bitmap of a static view and quickly composite it during each frame. Rasterization incurs an off-screen drawing pass and the bitmap consumes memory. Test and measure when using this property. | |
isTVSelectable | boolean | No | *(Apple TV only)* When set to true, this view will be focusable and navigable using the Apple TV remote. @platform ios | |
hasTVPreferredFocus | boolean | No | *(Apple TV only)* May be set to true to force the Apple TV focus engine to move focus to this view. @platform ios | |
tvParallaxShiftDistanceX | number | No | *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 2.0. @platform ios | |
tvParallaxShiftDistanceY | number | No | *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 2.0. @platform ios | |
tvParallaxTiltAngle | number | No | *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 0.05. @platform ios | |
tvParallaxMagnification | number | No | *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 1.0. @platform ios | |
onStartShouldSetResponder | (event: GestureResponderEvent) => boolean | No | Does this view want to become responder on the start of a touch? | |
onMoveShouldSetResponder | (event: GestureResponderEvent) => boolean | No | Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness? | |
onResponderEnd | (event: GestureResponderEvent) => void | No | If the View returns true and attempts to become the responder, one of the following will happen: | |
onResponderGrant | (event: GestureResponderEvent) => void | No | The View is now responding for touch events. This is the time to highlight and show the user what is happening | |
onResponderReject | (event: GestureResponderEvent) => void | No | Something else is the responder right now and will not release it | |
onResponderMove | (event: GestureResponderEvent) => void | No | The user is moving their finger | |
onResponderRelease | (event: GestureResponderEvent) => void | No | Fired at the end of the touch, ie "touchUp" | |
onResponderStart | (event: GestureResponderEvent) => void | No | ||
onResponderTerminationRequest | (event: GestureResponderEvent) => boolean | No | Something else wants to become responder. Should this view release the responder? Returning true allows release | |
onResponderTerminate | (event: GestureResponderEvent) => void | No | The responder has been taken from the View. Might be taken by other views after a call to onResponderTerminationRequest, or might be taken by the OS without asking (happens with control center/ notification center on iOS) | |
onStartShouldSetResponderCapture | (event: GestureResponderEvent) => boolean | No | onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, where the deepest node is called first. That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. This is desirable in most cases, because it makes sure all controls and buttons are usable. However, sometimes a parent will want to make sure that it becomes responder. This can be handled by using the capture phase. Before the responder system bubbles up from the deepest component, it will do a capture phase, firing on*ShouldSetResponderCapture. So if a parent View wants to prevent the child from becoming responder on a touch start, it should have a onStartShouldSetResponderCapture handler which returns true. | |
onMoveShouldSetResponderCapture | (event: GestureResponderEvent) => boolean | No | onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, where the deepest node is called first. That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. This is desirable in most cases, because it makes sure all controls and buttons are usable. However, sometimes a parent will want to make sure that it becomes responder. This can be handled by using the capture phase. Before the responder system bubbles up from the deepest component, it will do a capture phase, firing on*ShouldSetResponderCapture. So if a parent View wants to prevent the child from becoming responder on a touch start, it should have a onStartShouldSetResponderCapture handler which returns true. | |
onTouchStart | (event: GestureResponderEvent) => void | No | ||
onTouchMove | (event: GestureResponderEvent) => void | No | ||
onTouchEnd | (event: GestureResponderEvent) => void | No | ||
onTouchCancel | (event: GestureResponderEvent) => void | No | ||
onTouchEndCapture | (event: GestureResponderEvent) => void | No | ||
onPointerEnter | (event: PointerEvent) => void | No | ||
onPointerEnterCapture | (event: PointerEvent) => void | No | ||
onPointerLeave | (event: PointerEvent) => void | No | ||
onPointerLeaveCapture | (event: PointerEvent) => void | No | ||
onPointerMove | (event: PointerEvent) => void | No | ||
onPointerMoveCapture | (event: PointerEvent) => void | No | ||
onPointerCancel | (event: PointerEvent) => void | No | ||
onPointerCancelCapture | (event: PointerEvent) => void | No | ||
onPointerDown | (event: PointerEvent) => void | No | ||
onPointerDownCapture | (event: PointerEvent) => void | No | ||
onPointerUp | (event: PointerEvent) => void | No | ||
onPointerUpCapture | (event: PointerEvent) => void | No | ||
m | NumOrStrPx | No | set margin of this component | |
mt | NumOrStrPx | No | set margin top of this component | |
mr | NumOrStrPx | No | set margin right of this component | |
mb | NumOrStrPx | No | set margin bottom of this component | |
ml | NumOrStrPx | No | set margin left of this component | |
mx | NumOrStrPx | No | set margin right and left of this component | |
my | NumOrStrPx | No | set margin top and bottom of this component | |
p | NumOrStrPx | No | set padding of this component | |
pt | NumOrStrPx | No | set padding top of this component | |
pr | NumOrStrPx | No | set padding right of this component | |
pb | NumOrStrPx | No | set padding bottom of this component | |
pl | NumOrStrPx | No | set padding left of this component | |
px | NumOrStrPx | No | set padding right and left of this component | |
py | NumOrStrPx | No | set padding top and bottom of this component | |
top | string | number | No | sets the number of logical pixels to offset the top edge of this component | |
left | string | number | No | sets the number of logical pixels to offset the left edge of this component | |
right | string | number | No | sets the number of logical pixels to offset the right edge of this component | |
bottom | string | number | No | sets the number of logical pixels to offset the bottom edge of this component | |
position | "relative" | "absolute" | No | sets the positioning to relative or absolute of this component | |
display | "none" | "flex" | No | sets the display type of this component | |
flex | number | No | sets the flex property of this component | |
flexGrow | number | No | describes how any space within a container should be distributed among its children along the main axis | |
flexShrink | number | No | flexShrink describes how to shrink children along the main axis in the case in which the total size of the children overflows the size of the container on the main axis | |
flexWrap | "wrap" | "nowrap" | "wrap-reverse" | No | controls whether children can wrap around after they hit the end of a flex container | |
flexDirection | "row" | "column" | No | controls which directions children of a container go | |
gap | number | No | sets the gaps between rows and columns | |
overflow | "hidden" | "visible" | "scroll" | No | controls how children are measured and displayed | |
justifyContent | "center" | "flex-start" | "flex-end" | "space-between" | No | aligns children in the main direction | |
alignItems | "center" | "flex-start" | "flex-end" | No | aligns children in the cross direction | |
alignSelf | "auto" | FlexAlignType | No | controls how a child aligns in the cross direction, overriding the alignItems of the parent | |
width | string | number | No | sets the width of this component | |
minWidth | string | number | No | sets the min width of this component | |
height | string | number | No | sets the height of this component | |
minHeight | string | number | No | sets the min height of this component | |
textAlign | "left" | "right" | "center" | No | alings the text of this component | |
backgroundColor | BackgroundVariant | No | sets the background color of this component | |
opacity | number | No | sets the opacity of this component | |
borderWidth | BorderWidths | No | sets the border width of this component | |
borderColor | BorderColorVariant | No | sets the border color of this component | |
borderStyle | BorderStyles | No | sets the border style of this component | |
borderBottomWidth | BorderWidths | No | sets the bottom border's width of this component | |
borderBottomColor | BorderColorVariant | No | sets the bottom border's color of this component | |
borderTopWidth | BorderWidths | No | sets the top border's width of this component | |
borderTopColor | BorderColorVariant | No | sets the top border's color of this component | |
borderRightWidth | BorderWidths | No | sets the right border's width of this component | |
borderRightColor | BorderColorVariant | No | sets the right border's color of this component | |
borderLeftWidth | BorderWidths | No | sets the left border's width of this component | |
borderLeftColor | BorderColorVariant | No | sets the left border's color of this component | |
borderRadius | string | number | No | sets the border's radius of this component | |
borderRadiusTop | string | number | No | sets the border radius just for the top of the component | |
borderRadiusBottom | string | number | No | sets the border radius just for the bottom of the component | |
color | ColorVariant | No | Defaults to primary text | |
variant | string | number | symbol | No | Defaults to regular | |
textTransform | "none" | "uppercase" | "lowercase" | "capitalize" | No | The text transformation | |
textDecoration | "none" | "underline" | "line-through" | "underline line-through" | No | text decoration | |
textDecorationColor | ColorVariant | No | text decoration color | |
onPress | () => void | No | onPress callback | |
allowFontScaling | boolean | No | if false font won't scale if screen font size changes | |
selectable | boolean | false | No | if true the text will be selectable |
numberOfLines | number | No | if set, sets the number of lines the text will render on. if the text exceeds the line amount, it will ellipsis | |
maxFontSizeMultiplier | number | No | Max size for font when user adjusts their font scaling | |
paragraphSpacing | boolean | false | No | if true apply paragraphSpacing, it overrides the mb if supplied |
How to use the TextView component
<TextView variant="MobileBody" color="primary">My Text</TextView>
<TextView m={2}>My Text</TextView>
Full code for the TextView component
import React, { FC } from 'react'
import { AccessibilityProps, Pressable, Text } from 'react-native'
import { useSelector } from 'react-redux'
import styled from 'styled-components'
import { RootState } from 'store'
import { AccessibilityState } from 'store/slices/accessibilitySlice'
import { VAButtonTextColors, VATextColors, VATheme, VATypographyThemeVariants } from 'styles/theme'
import { useTheme } from 'utils/hooks'
import { themeFn } from 'utils/theme'
import { BoxProps, createBoxStyles } from './Box'
/** TextView font variants */
export type FontVariant = keyof VATypographyThemeVariants
export type ColorVariant = keyof VATextColors | keyof VAButtonTextColors
/**
* Props for textView
*/
export type TextViewProps = AccessibilityProps &
BoxProps & {
/** Defaults to primary text */
color?: ColorVariant
/** Defaults to regular */
variant?: FontVariant
/** The text transformation */
textTransform?: 'none' | 'uppercase' | 'lowercase' | 'capitalize'
/** text decoration */
textDecoration?: 'none' | 'underline' | 'line-through' | 'underline line-through'
/** text decoration color */
textDecorationColor?: ColorVariant
/** onPress callback */
onPress?: () => void
/** if false font won't scale if screen font size changes */
allowFontScaling?: boolean
/** if true the text will be selectable */
selectable?: boolean
/** if set, sets the number of lines the text will render on. if the text exceeds the line amount, it will ellipsis */
numberOfLines?: number
/** Max size for font when user adjusts their font scaling */
maxFontSizeMultiplier?: number
/** if true apply paragraphSpacing, it overrides the mb if supplied*/
paragraphSpacing?: boolean
/** Optional TestID */
testID?: string
}
const getColor = (theme: VATheme, props: TextViewProps): string => {
return (
theme.colors.text[props.color as keyof VATextColors] ||
theme.colors.buttonText[props.color as keyof VAButtonTextColors] ||
''
)
}
const getFontFamily = (theme: VATheme, props: TextViewProps): string => {
return theme.typography[props.variant as keyof VATypographyThemeVariants] || theme.typography.MobileBody
}
/** function to get fontsize from variant string:
* 1.It matches to the part font-size:..px in the string and extracts that part out for the next step
* 2.It then replaces all non number instances with an empty string
* 3.The + operator coerces it to a number type so that we can use it to multiply and get the spacing needed
*/
const getFontSize = (variant: string) => {
return +(
variant
.match(/font-size:..px/)
?.toString()
.replace(/[^0-9]/g, '') || 0
)
}
const getTextDecorationColor = (theme: VATheme, props: TextViewProps): string => {
return (
theme.colors.text[props.textDecorationColor as keyof VATextColors] ||
theme.colors.buttonText[props.textDecorationColor as keyof VAButtonTextColors] ||
''
)
}
const StyledText = styled(Text)`
${themeFn<TextViewProps>(getFontFamily)}
${themeFn<TextViewProps>((theme, props) => (props.color ? `color:${getColor(theme, props)};` : ''))}
${themeFn<TextViewProps>((theme, props) => createBoxStyles(theme, props))};
${themeFn<TextViewProps>((_theme, props) => (props.textTransform ? `text-transform:${props.textTransform};` : ''))}
${themeFn<TextViewProps>((_theme, props) => (props.textDecoration ? `text-decoration:${props.textDecoration}` : ''))};
${themeFn<TextViewProps>((theme, props) =>
props.textDecorationColor ? `text-decoration-color:${getTextDecorationColor(theme, props)}` : '',
)};
`
/**
* A common component for styling text in the application. It also conforms to the Box properties
* so you don't need to wrap it with a Box view for margins / paddings
*
* @returns TextView component
*/
const TextView: FC<TextViewProps> = ({ selectable = false, paragraphSpacing = false, testID, ...props }) => {
const { isVoiceOverTalkBackRunning } = useSelector<RootState, AccessibilityState>((state) => state.accessibility)
const theme = useTheme()
const wrapperProps = { ...props }
if (paragraphSpacing) {
const variant = getFontFamily(theme, wrapperProps)
const fontSize = getFontSize(variant)
wrapperProps.mb = fontSize * 2
}
if (wrapperProps.onPress) {
const { onPress, ...remainingProps } = wrapperProps
return (
<Pressable onPress={onPress} accessible={false}>
<StyledText testID={testID} {...remainingProps} />
</Pressable>
)
}
const selectToCopyProps = isVoiceOverTalkBackRunning
? {}
: { selectable, selectionColor: theme.colors.selectCopyText }
return <StyledText testID={testID} {...selectToCopyProps} {...wrapperProps} />
}
export default TextView