2

I'm trying to present data and
the json data contains html tags. so it's shown like this in the
browser

<ul><li>Marcus</li><li>19year old</li></ul>

it literally contains html tags as text.

data['id'].map((v)=>(
   <div>{v.name}</div>
   <div>{v.age}</div>
))

in react how can I show only text?

bonlim
  • 163
  • 9
  • You could use regex to extract out the tags. I'm terrible at regex, but you should be able to google it. You could also create an element from the string with javascript API's and then pull the innertext of the element you created. – Yatrix Apr 08 '21 at 02:29

2 Answers2

0

Ideally you would show us an example of the json data, without seeing that this answer might not be that helpful.

You can use dangerouslySetInnerHTML to render a html string as if it were actually HTML:

const data = [
  { name: "<li>Marcus</li>", age: "<li>19 year old</li>" },
  { name: "<li>Jane</li>", age: "<li>22 year old</li>" }
];

export default function App() {
  return (
    <div className="App">
      {data.map((v) => (
        <>
          <div dangerouslySetInnerHTML={{ __html: v.name }} />
          <div dangerouslySetInnerHTML={{ __html: v.age }} />
        </>
      ))}
    </div>
  );
}

Codesandbox: https://codesandbox.io/s/wandering-dream-vhprd?file=/src/App.js

LevPewPew
  • 159
  • 7
0

I solved it by using
yarn add react-html-parser
I got an advice from here
Render HTML string as real HTML in a React component
you can use this like below.

import ReactHtmlParser from 'react-html-parser';

const Component = (props) => {
   const {data} = props;
   return(
    <div>{ReactHtmlParser(data.title)}</div>
    {/* this will show bold text of hello instead of <b>hello</b> or any 
        other html form of json data */}
     )
   }

bonlim
  • 163
  • 9