Search code examples
reactjsdangerouslysetinnerhtml

Add Icon in dangerously set Inner html in React


I am trying to add a icon in between string text using dangerously set inner html while div tag is working but arrow icon right (from material ui) is not working it. also noticed that it turns to lower case when actual html is rendered.

here is my code one of the strPath is "World->Americas->Latin America and the Caribbean"

let keyArray = Object.keys(selectedRegionsLocal);
    let listUI = [];
    for (let i = 0; i < keyArray.length; i++) {
        let strPath = selectedRegionsLocal[keyArray[i]].path;
        const pieces = strPath.split("->");
        let result = pieces.join(" <ArrowRightIcon></ArrowRightIcon> ")
        let fresult = '<div>' + result + '</div>';
        console.log('result ', fresult);
        listUI.push(
            <Grid dangerouslySetInnerHTML={{ __html: fresult }} />
        )
    }
    return listUI;

this is what i am getting in dev tools -> element section

enter image description here

image of actual value

enter image description here

what can i do to turn the above actual value to this

enter image description here


Solution

  • You can simply put an icon on each item:

    Assume that your keyArray is something like this:

    const keyArray = ["World", "Americas", "South", "America"];
    

    Now, you can use map function to add an icon for each item:

    const result = data.map((item, i) => (
      <div key={i}>
        <ArrowRightIcon />
        <span>{item}</span>
      </div>
    ));
    

    the result

    Now, the result is ready to use, with a parent div and flex style, the final result will be produced:

    <div style={{ display: "flex" }}>{result}</div>
    

    final result