When you get a response from open ai after making api call. it will return a json stringified response and when you render it in a React component, it’s not properly formatted.
for example. if the responses contains numbered list, bullet points, or asterisk list. they’re not breaking or creating a newline. Also it doesn’t detects a a new paragraph for example. and if there’s a URL, it’s not clickable, and not shortened. the response is just being rendered as is. by the way, i’m rendering the response in a react chat container and i’m trying to avoid using dangerously inner html.
Any ideas what are the other approach for this to properly format the json response? Or is there like a package that do this?
tried dangerously inner html but this is risky.
2
Answers
We should not use "dangerously inner html" in ReactJS, Check out this link for more info: https://stackoverflow.com/a/60051861/21957513
I know these two ways to render HTML in ReactJS:
Sample code:
Sample code:
Now, I highly recommend opting for the second option, using react-markdown, Because react-markdown builds a virtual DOM, so React only replaces what changed, from a syntax tree. And, most importantly – It have more community support and widely adopted.
Let me know, if you’ve any questions.
If your JSON response contains HTML-like elements (e.g., numbered lists, bullet points, URLs), and you want to render them as React elements, you may need to preprocess the JSON data before passing it to
react-json-view
. You can use a library likereact-html-parser
to convert HTML strings into React elements:or
Then, you can use it in your component: