0

I want to return my string as html for react child assuming string as "<div><span>test</span></div>" and assuming we have a react function component like below:

 function StrToElement({ str }) {  
 const element = new DOMParser().parseFromString(str, "text/html").body.childNodes[0];
 return <pre>{element}</pre>;
}

but the above code throws this error:

Error: Objects are not valid as a React child (found: [object Text])

4
  • What is the type of element when you inspect it in the debugger? I’m guessing it’s not a string, which is why React is complaining. Commented Apr 10, 2022 at 20:01
  • when i use console.log(element) it return <div><span>test</span></div> but when i use typeof element it return object Commented Apr 10, 2022 at 20:03
  • Right. I’m guessing that’s your problem. I believe you need to to convert element to a string in some way before putting it into a <pre> tag body in that way, which would explain the error. Maybe try setting element to “test” and see if it works, and if so then try converting the original element object to a string (not sure the best way)? Commented Apr 10, 2022 at 20:06
  • i want a way that it work like a html tag not just as string. if i pass it as simple string it will not behave like a real tag Commented Apr 10, 2022 at 20:12

1 Answer 1

1

You may use dangerouslySetInnerHTML property inside your element.

It will look like this

 function StrToElement({ str }) { 
   return <div dangerouslySetInnerHTML={{__html: str}}>{element}</div>;
 }

or maybe you could assign it directly without creating new component

Reference

Sign up to request clarification or add additional context in comments.

1 Comment

word dangerously refer to =>(it is not safe way)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.