Syed Noman Ahmed
Syed Noman Ahmed

Reputation: 103

How to render html tags as html tags instead of string if they are coming from an array in React Component?

For example, I have an array of 3 values in it. The values also have some html tags. When I try to map through that array and try to display each of my array item, the values are displayed as it is. I want the HTML tags in my array values to be executed as true html elements. Below is my App.js code of my sample react app:

const App = () => {
  const [questions, setQuestions] = useState([
    "<h1>Test 1</h1>",
    "<h1>Test 2</h1>",
    "<h1>Test 3</h1>",
  ]);

  return (
    <div>
      {questions.map((question) => (
         <div>{question}</div>
      ))}
    </div>
  );
};

export default App;

The above react component give me my output as following:

<h1>Test 1</h1>
<h1>Test 2</h1>
<h1>Test 3</h1>

However, I want my final output to be look like below in which the html h1 tags are applied on my array elements when displayed in the browser. I know if I write such sort of html tags in a vanilla javascript, the html page renders it correctly by automatically reading any html tags as true html tags but I dont know how to achieve it in React Component.

Test 1

Test 2

Test 3

Upvotes: 1

Views: 4575

Answers (1)

Kanishk Anand
Kanishk Anand

Reputation: 1702

You can use dangerouslySetInnerHTML(question) inside your map function instead of the <div>{question}</div> inside the render to get the desired behavior, but please be cautious while using it. It can lead to unwanted security risk (hence the name) like XSS.

More information: https://reactjs.org/docs/dom-elements.html

Upvotes: 1

Related Questions