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
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉
