Revolutionary Citron
Revolutionary Citron

Reputation: 115

How to render HTML tags in JSX when pulling a string from a database

I'm creating a React.js project and I want to pull a string from Firebase that has HTML tags and render those tags. However, when I render the string as a string interpolation inside of a JSX element, the HTML tags simply print as text instead of actually taking effect.

Here is the code:


    import React from 'react';
    import styled from 'styled-components';
    import { firestore } from '../../firebase/firebase.utils';
    
    const name = firestore.collection('blog-categories').doc('8uVaHd22tT5oXSzpOOuj').get().then(doc => 
    doc.get('name'));
    
    class Economics extends React.Component {
      constructor() {
        super();
    
        this.state = {
          name: '',
          image: '',
          whyRead: ''
        }
      }
    
      componentDidMount() {
        firestore.collection('blog-categories').doc('8uVaHd22tT5oXSzpOOuj').get().then(doc => {
          this.setState({ name: doc.get('name'), image: doc.get('image'), whyRead: doc.get('why-read') 
          });
        });
      }
    
    
      render() {
        return (
          <div>
            <h1>{ `${this.state.whyRead}` }</h1>
          </div>
        )
      }
    }
    
    export default Economics;

When I run this code, the result is simply the following:

enter image description here

However, I want the HTML bold tags to actually take effect and create bold text. How would I do this?

Upvotes: 0

Views: 2748

Answers (1)

ludwiguer
ludwiguer

Reputation: 2245

dangerouslySetInnerHTML

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.

https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

return <div dangerouslySetInnerHTML={{__html: this.state.whyRead}} />;

Upvotes: 2

Related Questions