React: Get text content of React element
28 August 2023 (Updated 11 August 2024)
import ReactDOMServer from 'react-dom/server'
// Get text content of React element
export function getNodeText(
node: React.ReactElement | string | number,
): string {
const nodeHtml = ReactDOMServer.renderToString(node)
const wrapperElement = document.createElement('div')
wrapperElement.innerHTML = nodeHtml
return wrapperElement.textContent || ''
}
Tagged:
React
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment