Home > Enterprise >  How to parse link texts to html in React
How to parse link texts to html in React

Time:12-18

Hi I have the following data returned from an API service as social media handles. I console.log the returned data and got the following.

0: {type: 'facebook', handle: 'www.facebook.com/username'} 1: {type: 'twitter', handle: 'www.twitter.com/username'} length: 2 [[Prototype]]: Array(0)

I need it to be represented on the web page as a normal html link with the social media icons showing as follows:

<a href="www.facebook.com/username"><i className="bi bi-facebook"></i></a>
<a href="www.twitter.com/username"><i className="bi bi-twitter"></i></a>

I have tried the following

const socialMediaLinks=socialMediaHandles.map(handle => `<a href='${handle.handle}'>
<i className='bi-bi-${handle.type}'></i></a>`)

I then go to where I want it to display on the component and paste the following code

{socialMediaLinks}

but when I do that, the text is returned just as text and not rendered as html on the page.

I am using React functional component.

I am actually new to React and trying to figure out how to achieve this. I will appreciate any guide. Thank you

CodePudding user response:

While there are ways to inject strings of HTML into a React application, they are error prone and dangerous.

Don't generate strings of HTML.

You're using JSX already, use JSX there too.

const socialMediaLinks=socialMediaHandles.map(handle => (
    <a href={handle.handle}>
        <i className={`bi-bi-${handle.type}`}></i>
    </a>
));
  • Related