skip to Main Content

How to convert received JSON data to HTML tags in React?

my code:

{JSON.stringify(setData.Element_008.value?.Element_001)}

# in Element_008
{
    "type": "ItemPartBox",
    "value": {
        "Element_000": "<FONT COLOR='#A9D0F5'>세트 효과 레벨</FONT>",
        "Element_001": "사멸 <FONT COLOR='#FFD200'>Lv.3</FONT>"
    }
}

I want to apply the font tag in text

I tried JSON data to stringify data. but I want font tag…

2

Answers


  1. Use the dangerouslySetInnerHTML prop to insert the HTML from your JSON data into a React element.

    const renderedHTMLElements = useMemo(() => {
        const htmlElements = [];
        const data = setData.Element_008.value;
    
        for (const key in data) {
          if (data.hasOwnProperty(key)) {
            const html = { __html: data[key] };
            htmlElements.push(
              <div key={key} dangerouslySetInnerHTML={html}></div>
            );
          }
        }
    
        return htmlElements;
      }, [])
    
      return (
        <div>
          {renderedHTMLElements}
        </div>
      );
    
    Login or Signup to reply.
  2. You can use the dangerouslySetInnerHTML prop to inject HTML text into an element, but be sure to sanitize your input before assigning the __html value.

    For demonstration purposes, I chose the HtmlSanitizer library. It works out-of-the-box in the browser.

    const { useEffect, useState } = React;
    
    const sanitize  = (input) => HtmlSanitizer.SanitizeHtml(input);
    const fetchData = ()      => Promise.resolve(MOCK_DATA);
    
    const App = () => {
      const [data, setData] = useState({});
    
      useEffect(() => {
        fetchData().then(setData);
      }, []);
    
      return (
        <div>
          {
            /* Conditinally render the <ul> */
            data.Element_008 != null && (
              <ul>
                {Object.entries(data.Element_008.value).map(([key, value]) => (
                  <li
                    key={key}
                    dangerouslySetInnerHTML={{ __html: sanitize(value) }}
                  ></li>
                ))}
              </ul>
            )
          }
        </div>
      );
    };
    
    const MOCK_DATA = {
      Element_008: {
        type: "ItemPartBox",
        value: {
          Element_000: "<FONT COLOR='#A9D0F5'>세트 효과 레벨</FONT>",
          Element_001: "사멸 <FONT COLOR='#FFD200'>Lv.3</FONT>",
        },
      },
    };
    
    ReactDOM.createRoot(document.getElementById("root")).render(<App />);
    <script src="https://cdn.jsdelivr.net/gh/jitbit/HtmlSanitizer@master/HtmlSanitizer.js"></script>
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search