Home > OS >  Json map in React Js
Json map in React Js

Time:08-24

How can map the json in react js

======================

const temp1 = [
       {
          code:"<h1>Hai</h1>",
          img: "<img src='https://www.sitesaga.com/wp-content/uploads/2020/04/what-is-website-how-it-works.png' className='img'/>",
        },
        {
          code:"<h1>World</h1>",
          img: "<img src='https://ceblog.s3.amazonaws.com/wp-content/uploads/2018/08/28183850/home_post_2.gif' className='img'/>",
        }
      ];

============================

CodePudding user response:

If you want to map and render the html you can map and use dangerouslySetInnerHTML

const temp1 = [{
    code: "<h1>Hai</h1>",
    img: "<img src='https://www.sitesaga.com/wp-content/uploads/2020/04/what-is-website-how-it-works.png' className='img'/>",
  },
  {
    code: "<h1>World</h1>",
    img: "<img src='https://ceblog.s3.amazonaws.com/wp-content/uploads/2018/08/28183850/home_post_2.gif' className='img'/>",
  }
]

const Component = () => {
  return (
    <>
      temp1.map(el => (
        <div key={el.code} dangerouslySetInnerHTML={{__html: `${el.code}${el.img}`}} />)
      )
    </>
  )
}

CodePudding user response:

To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property :

return (
    <div>
      {temp.map(({code, img}, index) => (
        <div key={index}>
          <div dangerouslySetInnerHTML={{ __html: code }} />
          <div dangerouslySetInnerHTML={{ __html: img }} />
        </div>
        ))}
    </div>

CodePudding user response:

   import Image1 from "./images/image1.jpg"
   import Image2 from './images/image2.jpg'
   const temp1 = [
    {
      code_content : 'Hello',
      img_src : Image1 
    },
    {
      code_content : 'World',
      img_src : Image2
    }
   ]
   const App = () => {
    return <div>
      {temp1.map((item) => {
        <>
          <h1>{item.code_content}</h1>
          <img src={item.img_src} />
        </>
      })}
    </div>
   }
  • Related