javascriptreactjs

extract plain text from react object


somebody knows how could I extract plain text from a react component?

example:

const reactObject = 
  <div className="text-primary">
    <span>this is a react object, </span>
    <b>builded with jsx!!!!</b>
  </div>;
.....
//what should I do inside extractText????
const plainText = extractText(reactObject);
alert(reactObject);//result: "[Object object]"
alert(plainText);// must result: "this is a react object builded with jsx!!!!"

Solution

  • I have write this recursive function if someone needs

      extractString(obj) {
        if (typeof obj === 'string') return obj;
        else if (React.isValidElement(obj)) {
          return this.extractString(obj.props.children);
        } else if (Array.isArray(obj)) {
          return obj.map(e => this.extractString(e)).join(' ');
        } else return obj.toString();
      }
    

    I'm using this for show error message at bottom of an input:

    <input ref={.....} value={....} ..... />
    <p>{this.props.errorMessage}</p>
    

    BUUUUUT if the user still click on the submit button... I want to show the same text in the default browser error message without rewrite setting the same massage only once.

    const errorMessage = this.extractString(this.props.errorMessage);
    //this is the ref to the input
    this.input.current.setCustomValidity(errorMessage);