Home > Net >  extract plain text from react object
extract plain text from react object

Time:03-29

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!!!!"

CodePudding user response:

I really don't know why do you need this, but like were told you in the comments, you can use the useRef for your component, and if you know very well the component structure you can get its children and iterate to get the innerHTML. You you need a generic solution, you should provide some more information.

Here is a stackblitz code solving your specific problem (you can open the console to see the log):

https://stackblitz.com/edit/react-ts-n47abv?file=index.tsx

CodePudding user response:

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);
  • Related