Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text content from React element stored in a variable

Is there a way to get text content from a React element stored in a variable without ref?

There is a functional component, that receives title prop, which contains react element:

function component({ title }) {
 const content = title.textContent() // Need Something like this
}

and this title prop might have react node like: <div>Some Title</div>. But I'd like to get only content of the node, in a variable before rendering it. Is it possible?

When I console.log title variable this is the output, The content I want is inside props.children array, so is there a method to get it without traversing through keys:

enter image description here

like image 644
Rahul Sagore Avatar asked Apr 17 '26 05:04

Rahul Sagore


2 Answers

I've not found a better solution than indeed traversing the object to get the text. In TypeScript:

/**
 * Traverse any props.children to get their combined text content.
 *
 * This does not add whitespace for readability: `<p>Hello <em>world</em>!</p>`
 * yields `Hello world!` as expected, but `<p>Hello</p><p>world</p>` returns
 * `Helloworld`, just like https://mdn.io/Node/textContent does.
 *
 * NOTE: This may be very dependent on the internals of React.
 */
function textContent(elem: React.ReactElement | string): string {
  if (!elem) {
    return '';
  }
  if (typeof elem === 'string') {
    return elem;
  }
  // Debugging for basic content shows that props.children, if any, is either a
  // ReactElement, or a string, or an Array with any combination. Like for
  // `<p>Hello <em>world</em>!</p>`:
  //
  //   $$typeof: Symbol(react.element)
  //   type: "p"
  //   props:
  //     children:
  //       - "Hello "
  //       - $$typeof: Symbol(react.element)
  //         type: "em"
  //         props:
  //           children: "world"
  //       - "!"
  const children = elem.props && elem.props.children;
  if (children instanceof Array) {
    return children.map(textContent).join('');
  }
  return textContent(children);
}

I don't like it at all, and hope there's a better solution.

like image 105
Arjan Avatar answered Apr 18 '26 17:04

Arjan


use https://github.com/fernandopasik/react-children-utilities

import Children from 'react-children-utilities'


const MyComponent = ({ children }) => Children.onlyText(children)

from https://github.com/facebook/react/issues/9255

like image 30
Moe Singh Avatar answered Apr 18 '26 19:04

Moe Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!