React innerText Extractor

1.1.5 · active · verified Sun Apr 19

react-innertext is a utility package designed to extract the plain text content from React JSX objects, mimicking the behavior of the native DOM `innerText` property. It recursively traverses React elements, including children and fragments, to produce a single, concatenated string. This is particularly useful for scenarios requiring a plain text representation of complex React component trees, such as generating `title` attributes, SEO metadata, or for accessibility purposes where only the text content is needed. The current stable version is 1.1.5. While its release cadence appears infrequent based on the provided history, the project is maintained, with recent updates (v1.1.4) addressing Node.js compatibility and incorporating built-in TypeScript definitions. Its key differentiator is its straightforward API for handling React's virtual DOM, providing a direct equivalent to `innerText` without requiring a full DOM render or complex parsing logic.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use `react-innertext` to extract plain text from complex JSX structures, including a practical application in a component's `title` attribute.

import innerText from 'react-innertext';
import React from 'react';

function MyComponent() {
  const children = (
    <div>
      Hello <strong>world</strong>!
      I am <span children={3} /> years old!
    </div>
  );

  const extractedText = innerText(children);
  console.log(extractedText); // Expected: 'Hello world! I am 3 years old!'

  // A practical example: using innerText for a title attribute
  function MyTableHeaderCell({ children }) {
    return (
      <th
        children={children}
        title={innerText(children)}
      />
    );
  }

  return (
    <div>
      <p>Original JSX:</p>
      {children}
      <p>Extracted text: {extractedText}</p>
      <table>
        <thead>
          <tr>
            <MyTableHeaderCell>
              <b>Username</b>
            </MyTableHeaderCell>
          </tr>
        </thead>
      </table>
    </div>
  );
}

// In a real application, you would render MyComponent
// ReactDOM.render(<MyComponent />, document.getElementById('root'));

view raw JSON →