React: How to format text within a string with ‘dangerouslySetInnerHTML’

Trisha Pan
2 min readJul 27, 2021

This article is for if you want to be able to pass in the string value “Hello, <em>world</em>!” in React, and have the styling tags convert into actual styling, instead of showing up as text.

Customize your text, like in a build-a-bear workshop. Except more dangerous. Photo by Marco Secchi.

Here’s a sample use case:

You have an ‘About the Team’ page and a modular component for displaying each of your 3 or 20 team members’ profiles, so that if you wanted to update the universal formatting, you’d only have to update it once. However, within the description for each person, you want to add line breaks or any other type of in-line styling, but not everyone’s description will have styling in the same places.

Below is a simplified vignette of what your code might look like. Below is 1. what your ‘profiles’ object might look like (where you update the information for each person), followed by 2. what your embedded React component might look like, followed by 3. what your render section might look like.

  1. ‘Profiles’ object where you would update any information about each person:
const profiles = [   {      name: 'Elyssa',      bio: 'Elyssa is a developer, writer, artist, and terrible picture-taker. She likes to draw, cook, and code. <br><br>She would like to thank her cat Cricket, for emotional support, and DnD, for just generally existing.'   },   {      name: 'Trisha Pan',      bio: 'Trisha is a software engineer with a background in management consulting, as well as chemical and biomedical engineering.<br><br>In her free time, she enjoys painting, backpacking, and doing improv.'   },   {      name: 'Yasaman',      bio: 'Yasaman is a software engineer in Los Angeles, CA with a passion for computer science and backend development. In her spare time, Yasaman enjoys reading books, listening to podcasts, and playing guitar'   }]

2. Embedded React component for displaying each profile:

const profileCards = profiles.map((person, i) => (   <div>      <h3>{person.name}</h3>      {/* Below allows us to escape HTML tags. */}      <p dangerouslySetInnerHTML={{ __html: person.bio }} /></div>))

3. Rendering your profiles:

return(
<div>
{profileCards}
</div>
)

To see what the above code might look like with styling and additional information, check out this Github page for the rest of our code.

--

--

Trisha Pan

Software Engineer with a passion for understanding and explaining things.