Getting the text content of a React node Fragment
Published on 2024-11-13 • Modified on 2024-11-13
This snippet shows how to get the text content of a React node Fragment. It is sometimes helpful to extract the text of the following React node <>text1</>
. In this case, the React node is a Fragment
with only one text child. Therefore, we can retrieve it with the following function:
function getTextFromSimpleFragment(node: ReactNode): string {
if (React.isValidElement(node) && node.type === React.Fragment) {
const children = node.props.children;
if (typeof children === 'string') {
return children;
}
}
return 'error: simple fragment expected';
}
More on Stackoverflow Read the doc Random snippet