Skip to content

Commit 12054e3

Browse files
DoberjohnMikitasK
andauthored
fix(text): inherit parent styles in nested Text (#5040)
* fix(text): keep the parent variant when nesting Text * docs(text): add nested Text example cases * fix(text): inherit the parent style in nested Text A nested Text or AnimatedText without a variant applied its fallback font unconditionally, overriding the font, weight, letter spacing and color it should have inherited from the enclosing text. React Native inherits these, so a nested one now declares only its own style. The shared context lives in its own module to keep the Text and AnimatedText imports one-directional. Fixes #4351. * docs(text): show inherited weight in the nested Text example * Update src/components/__tests__/Typography/Text.test.tsx Co-authored-by: Mikita Kliushun <nikita.kliushun@gmail.com> * Update src/components/Typography/Text.tsx Co-authored-by: Mikita Kliushun <nikita.kliushun@gmail.com> * perf(text): skip the nesting context when children cannot contain text * refactor(text): trim comments and simplify the nested children check Keep a comment only where it helps, in one line, and drop the context sentence that the nested font change made wrong. Check every child for an element instead of copying React Native's three-child cutoff. The provider is still skipped when the children are only strings or numbers. * test(text): consolidate the nested Text tests Assert that a nested Text sets no color of its own and inherits the parent's, and cover a Text nested through another component. Fold the test that did not check what its title said into the one above it, drop the duplicate of the default font test, and replace the three AnimatedText tests with one. * fix(text): respect the theme prop of a nested Text A nested Text or AnimatedText with its own theme renders like a top-level one again, with the theme's color, as it does on main. * fix(text): keep the parent color in a nested Text with a variant A nested Text or AnimatedText with a variant now applies only the variant font, so it no longer resets the color to onSurface. A Text with a variant inside a contained Button keeps the button's label color. * docs(text): show the nested Text examples after the custom variant The nested section was inserted above the Custom Variant sample, which made that sample read as one of the nested cases. * docs(migration): describe nested Text inheritance --------- Co-authored-by: Mikita Kliushun <nikita.kliushun@gmail.com>
1 parent b2aff97 commit 12054e3

6 files changed

Lines changed: 262 additions & 18 deletions

File tree

‎docs/6.x/docs/guides/migration.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,12 @@ An accordion with a `left` element now indents only its `List.Item` children. An
546546

547547
`theme` set on `List.Accordion` no longer reaches its children either. Pass it to the child that needs the override.
548548

549+
### Text
550+
551+
A `Text` nested in another `Text` now inherits the parent's font and color, as React Native's own `Text` does. In 5.x it reset them to the theme's default font and `onSurface`, so a `Text` with a variant inside a contained `Button` lost the button's label color, and a plain `Text` inside a `Chip` lost the chip's font. A nested `Text` with a `variant` still takes that variant's font, and its own `style` still wins over the parent's. To give a nested `Text` its own color, set `color` in its `style`, or pass it a `theme`, which makes it render like a top-level `Text`.
552+
553+
On iOS and Android, a `Text` inside a `View` inside a `Text` renders in the platform's default color, so set its `color` or pass it a `theme`.
554+
549555
### ToggleButton
550556

551557
`ToggleButton`, `ToggleButton.Group` and `ToggleButton.Row` were removed. For an

‎example/src/Examples/TextExample.tsx‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,27 @@ const TextExample = () => {
9090
Custom Variant
9191
</Text>
9292
</PaperProvider>
93+
94+
<Text style={styles.heading} variant="titleMedium">
95+
Nested text
96+
</Text>
97+
98+
<Text style={styles.text} variant="headlineSmall">
99+
<Text>Unstyled child, stays Headline Small</Text>
100+
</Text>
101+
<Text style={styles.text} variant="headlineSmall">
102+
<Text style={styles.nestedChild}>
103+
Styled child, italic but still Headline Small
104+
</Text>
105+
</Text>
106+
<Text style={styles.text} variant="headlineSmall">
107+
<Text variant="bodySmall">
108+
Child variant wins, renders Body Small
109+
</Text>
110+
</Text>
111+
<Text style={[styles.text, styles.boldParent]} variant="headlineSmall">
112+
Bold parent, <Text>and the nested child inherits the weight</Text>
113+
</Text>
93114
</View>
94115
</ScreenWrapper>
95116
);
@@ -104,6 +125,16 @@ const styles = StyleSheet.create({
104125
text: {
105126
marginVertical: 4,
106127
},
128+
heading: {
129+
marginTop: 24,
130+
marginBottom: 4,
131+
},
132+
nestedChild: {
133+
fontStyle: 'italic',
134+
},
135+
boldParent: {
136+
fontWeight: 'bold',
137+
},
107138
});
108139

109140
export default TextExample;

‎src/components/Typography/AnimatedText.tsx‎

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { StyleSheet } from 'react-native';
44

55
import Animated from 'react-native-reanimated';
66

7+
import { canContainNestedText, NestedTextContext } from './NestedTextContext';
78
import type { VariantProp } from './types';
89
import { useLocale } from '../../core/locale';
910
import { useInternalTheme } from '../../core/theming';
@@ -48,6 +49,10 @@ function AnimatedText({
4849
const theme = useInternalTheme(themeOverrides);
4950

5051
const { direction: writingDirection } = useLocale();
52+
// Nested text inherits the parent's style unless it has its own theme
53+
const inheritsStyle = React.useContext(NestedTextContext) && !themeOverrides;
54+
55+
let element: React.ReactElement;
5156

5257
if (variant) {
5358
const font = theme.fonts[variant];
@@ -59,25 +64,31 @@ function AnimatedText({
5964
);
6065
}
6166

62-
return (
67+
element = (
6368
<Animated.Text
6469
ref={ref}
6570
{...rest}
66-
style={[
67-
font,
68-
styles.text,
69-
{ writingDirection, color: theme.colors.onSurface },
70-
style,
71-
]}
71+
style={
72+
inheritsStyle
73+
? [font, style]
74+
: [
75+
font,
76+
styles.text,
77+
{ writingDirection, color: theme.colors.onSurface },
78+
style,
79+
]
80+
}
7281
/>
7382
);
83+
} else if (inheritsStyle) {
84+
element = <Animated.Text ref={ref} {...rest} style={style} />;
7485
} else {
7586
const font = theme.fonts.bodyMedium;
7687
const textStyle = {
7788
...font,
7889
color: theme.colors.onSurface,
7990
};
80-
return (
91+
element = (
8192
<Animated.Text
8293
ref={ref}
8394
{...rest}
@@ -92,6 +103,16 @@ function AnimatedText({
92103
/>
93104
);
94105
}
106+
107+
if (!canContainNestedText(rest.children)) {
108+
return element;
109+
}
110+
111+
return (
112+
<NestedTextContext.Provider value={true}>
113+
{element}
114+
</NestedTextContext.Provider>
115+
);
95116
}
96117

97118
const styles = StyleSheet.create({
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import * as React from 'react';
2+
3+
// Whether a text is rendered inside another text, so it can inherit its style
4+
export const NestedTextContext = React.createContext(false);
5+
6+
export const canContainNestedText = (children: unknown) =>
7+
Array.isArray(children)
8+
? children.some(
9+
(child: unknown) => child != null && typeof child === 'object'
10+
)
11+
: children != null && typeof children === 'object';

‎src/components/Typography/Text.tsx‎

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { StyleSheet, Text as NativeText } from 'react-native';
44
import type { StyleProp, TextStyle } from 'react-native';
55

66
import AnimatedText from './AnimatedText';
7+
import { canContainNestedText, NestedTextContext } from './NestedTextContext';
78
import type { VariantProp } from './types';
89
import { useLocale } from '../../core/locale';
910
import { useInternalTheme } from '../../core/theming';
@@ -90,11 +91,15 @@ const Text = ({
9091
// FIXME: destructure it in TS 4.6+
9192
const theme = useInternalTheme(initialTheme);
9293
const { direction: writingDirection } = useLocale();
94+
// Nested text inherits the parent's style unless it has its own theme
95+
const inheritsStyle = React.useContext(NestedTextContext) && !initialTheme;
9396

9497
React.useImperativeHandle(ref, () => ({
9598
setNativeProps: (args: Object) => root.current?.setNativeProps(args),
9699
}));
97100

101+
let element: React.ReactElement;
102+
98103
if (variant) {
99104
let font = theme.fonts[variant];
100105
let textStyle = [font, style];
@@ -111,7 +116,6 @@ const Text = ({
111116
// Context: Some components have the built-in `Text` component with a predefined variant,
112117
// that also accepts `children` as a `React.Node`. This can result in a situation,
113118
// where another `Text` component is rendered within the built-in `Text` component.
114-
// By doing that, we assume that user doesn't want to consume pre-defined font properties.
115119
// Case one: Nested `Text` has different `variant` that specified in parent. For example:
116120
// <Chip>
117121
// <Text variant="displayMedium">Nested</Text>
@@ -133,9 +137,9 @@ const Text = ({
133137
// <Text style={{fontSize: 30}}>Nested</Text>
134138
// </Chip>
135139
// Solution: To address the following scenario, the code below overrides the
136-
// parent's style with children's style:
140+
// parent's style with children's style, on top of the parent's variant:
137141
if (!props.variant) {
138-
textStyle = [style, props.style];
142+
textStyle = [font, style, props.style];
139143
}
140144
}
141145

@@ -147,31 +151,47 @@ const Text = ({
147151
);
148152
}
149153

150-
return (
154+
element = (
151155
<NativeText
152156
ref={root}
153-
style={[
154-
styles.text,
155-
{ writingDirection, color: theme.colors.onSurface },
156-
textStyle,
157-
]}
157+
style={
158+
inheritsStyle
159+
? textStyle
160+
: [
161+
styles.text,
162+
{ writingDirection, color: theme.colors.onSurface },
163+
textStyle,
164+
]
165+
}
158166
{...rest}
159167
/>
160168
);
169+
} else if (inheritsStyle) {
170+
element = <NativeText {...rest} ref={root} style={style} />;
161171
} else {
162172
const font = theme.fonts.default;
163173
const textStyle = {
164174
...font,
165175
color: theme.colors?.onSurface,
166176
};
167-
return (
177+
element = (
168178
<NativeText
169179
{...rest}
170180
ref={root}
171181
style={[styles.text, textStyle, { writingDirection }, style]}
172182
/>
173183
);
174184
}
185+
186+
if (!canContainNestedText(rest.children)) {
187+
return element;
188+
}
189+
190+
return (
191+
<NestedTextContext.Provider value={true}>
192+
{element}
193+
</NestedTextContext.Provider>
194+
);
175195
};
176196

177197
const styles = StyleSheet.create({

0 commit comments

Comments
 (0)