1

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

0

1 Answer 1

2

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>
));
Sign up to request clarification or add additional context in comments.

3 Comments

This worked perfectly the moment I used it. But all of a sudden it started showing "socialMediaHandles.map is not a function" and I never changed that variable. Any ideas as to what could be responsible please?
There's no way to tell how you changed the value of socialMediaHandles from the code you've provided. You could ask a new question. Don't forget to provide a minimal reproducible example.
Thank you very much. I have a condition to ensure that the returned variable is an array before trying to map through it as follows Array.isArray(socialMediaHandles)?socialMediaHandles.map(handle => ( <a href={https://${handle.handle}}> <i className={bi bi-${handle.type}}></i> </a> )):"No social media handles to display"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.