Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Is there something similar to node.textContent?

I'm trying to test a react component children and I wanted to get a text representation of its children.

Is there a tool that does something similar to node.textContent for React?

I would like to have something like this:

let testComponent = (
  <Test>
    <p>abc</p>
    <p>abc2</p>
  </Test>
);

expect(testComponent.props.children.toString()).to.equal('abc abc2');
like image 405
Alan Souza Avatar asked Dec 10 '15 14:12

Alan Souza


2 Answers

react-getNodeText Sandbox screenshot

const getNodeText = node => {
  if (['string', 'number'].includes(typeof node)) return node
  if (node instanceof Array) return node.map(getNodeText).join('')
  if (typeof node === 'object' && node) return getNodeText(node.props.children)
}

https://codesandbox.io/s/react-getnodetext-h21ss

  // in the picture
  {heading} // <Heading>Hello <span className="red">Code</span>Sandbox</Heading>
  <pre ref={printInnerHTML}/>
  <pre>{getNodeText(heading)}</pre>
like image 140
Qwerty Avatar answered Oct 13 '22 01:10

Qwerty


You can write a small function that traverses through the react element and gets you the text.

import React from 'react';
import renderer from 'react-test-renderer';

const MyComponent = ()=>{
  return <div>
    <p>hello</p>
    <div>
      <p>to</p>
    </div>
  </div>
}

const getText=(tree)=>{
  if(typeof tree === 'string'){
    return tree;
  }
  return tree.children.map((child)=>{
    return getText(child);
  }).join('');
}


it('renders without crashing', () => {
  const tree = renderer
    .create(<MyComponent />)
    .toJSON();

  expect(getText(tree)).toBe("helloto");
});

Here MyComponent is the component from which you need the text.

getText() will get all the text nodes from the component in the form of a string.

like image 38
Atul Avatar answered Oct 13 '22 00:10

Atul