I’m working on a React Native project and trying to render block content from Sanity.io using @sanity/block-content-to-react. Although the library mentions experimental support for React Native, I keep getting the following error:
"Text strings must be rendered within a <Text> component."
Code Context:
Here’s the setup for my component, FAQItem, where I’m trying to render the answer (which is Sanity block content) using @sanity/block-content-to-react:
import BlockContent from '@sanity/block-content-to-react';
import { Text, View, TouchableOpacity, LayoutAnimation, UIManager, Platform } from 'react-native';
import { useState } from 'react';
if (Platform.OS === 'android' && UIManager.setLayoutAnimationEnabledExperimental) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
const serializers = {
types: {
block: (props) => (
<Text>{props.children}</Text>
),
},
};
export function FAQItem({ question, answer }) {
const [isExpanded, setIsExpanded] = useState(false);
const toggleExpansion = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
setIsExpanded(!isExpanded);
};
return (
<View>
<TouchableOpacity onPress={toggleExpansion}>
<Text>{question}</Text>
</TouchableOpacity>
{isExpanded && (
<BlockContent blocks={answer} serializers={serializers} />
)}
</View>
);
}
What I’ve Tried:
I’ve added serializers, wrapping all text elements in , as shown above, to ensure compatibility.
I’ve tried different combinations of serializers for lists and list items, even wrapping all elements within tags.
Issue:
Despite these efforts, I’m still getting the error. It seems like some elements within BlockContent are not being wrapped correctly for React Native, causing issues.