Search code examples
reactjsjavascript-objectshtmlelements

How to add HTML elements in to JavaScript object and use in react


This is code in a JavaScript object

const AlbumDetails = [
{
    name: '<i class="fas fa-check">Basic</i>',
    price: '',
    details: [],
},
{ name: '<i class="fas fa-check">Intermediate</i>', price: '', details: [] },
{ name: '<i class="fas fa-check">Pro</i>', price: '', details: [] },
{ name: '<i class="fas fa-check">Ultimate</i>', price: '', details: [] },
];

export default AlbumDetails;

and I want to use this object like

const PriceCard = (props) => {
<div className="p-box">
                    
    <div className="p-content">
        <h2>{props.AlbumDetails[0].name}</h2>
        <h4>{props.AlbumDetails[0].price}</h4>
        
        
    </div>
</div>
}

so on. In the browser, it shows <i class="fas fa-check">Basic</i>, but I want only the icon and name "Basic" only. So how it could be done.


Solution

  • The HTML string can be inserted using dangerouslySetInnerHTML:

    <h2 dangerouslySetInnerHTML={{ __html: props.AlbumDetails[0].name }} />
    

    Note: you need to be satisfied that the HTML is safe (i.e is not formed from user input), otherwise you could open yourself up to XSS.