HighlightedText
Display text with customizable highlighted segments for real-time speech visualization.
The HighlightedText component allows you to display text with customizable highlighted segments. This is especially useful for emphasizing parts of text (e.g., the currently synthesized text). In addition to the specialized properties listed below, the component accepts all standard React Native <Text> props.
Importing the component
import {HighlightedText} from '@mhpdev/react-native-speech';Properties
| Property | Type | Description |
|---|---|---|
text | string | The full text content to be displayed. |
highlightedStyle | StyleProp<TextStyle> | The base style applied to all highlighted segments. Can be overridden per segment through highlights. |
highlights | Array<{start: number; end: number; style?: StyleProp<TextStyle>}> | The segments to highlight. Each entry must include start (starting character index) and end (ending index), plus an optional per-segment style. |
onHighlightedPress | (segment: {text: string; start: number; end: number}) => void | Invoked when a highlighted segment is pressed, with the segment's text, start, and end. |
Example
import React from 'react';
import {
HighlightedText,
type HighlightedSegmentProps,
type HighlightedSegmentArgs,
} from '@mhpdev/react-native-speech';
import {Alert, SafeAreaView, StyleSheet} from 'react-native';
const TEXT = 'This is a sample text where some parts are highlighted.';
const ExampleHighlightedText: React.FC = () => {
const highlights: Array<HighlightedSegmentProps> = [
{start: 10, end: 21},
{start: 43, end: 54, style: styles.customHighlightedStyle},
];
const onHighlightedPress = React.useCallback(
({text, start, end}: HighlightedSegmentArgs) =>
Alert.alert(
'Highlighted Segment',
`Segment "${text}" starts at ${start} and ends at ${end}`,
),
[],
);
return (
<SafeAreaView style={styles.container}>
<HighlightedText
text={TEXT}
style={styles.text}
highlights={highlights}
highlightedStyle={styles.highlighted}
onHighlightedPress={onHighlightedPress}
/>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
padding: 16,
},
text: {
fontSize: 16,
},
highlighted: {
backgroundColor: 'yellow',
fontWeight: 'bold',
},
customHighlightedStyle: {
color: 'white',
backgroundColor: 'blue',
},
});
export default ExampleHighlightedText;Driving highlights from speech progress
Combine the component with Speech.onProgress: every progress event reports the location and length of the currently spoken range, which can be passed as a highlight. See the examples page for the complete pattern used by the example project.