0

new to react. I am getting a JSON with this value

{
"unit": "G/ft²/yr"
}

I am setting it in a state variable and then using it to display in the title. I have done this in Django before and it converts it properly but I don't see that happening here so. am I sending the data wrong or is there a way to do this.

setUnit({
        water_flow_unit: item.unit
      });

<h4 className="baseline-graph-header">
   Unit({Unit.unit})
</h4>

it displays as G/ft&sup2;/yr but I want it converted. Any help is appreciated.

XCS
  • 27,244
  • 26
  • 101
  • 151
Damini Ganesh
  • 288
  • 1
  • 10
  • You want it converted to what? What is `Unit` ? – XCS May 21 '19 at 21:07
  • @Cristy Its just useState hook. const [Unit, setUnit] = useState("") – Damini Ganesh May 21 '19 at 21:09
  • Show the rest of your component code. – GifCo May 21 '19 at 21:09
  • @DaminiGanesh it should be [ unit, setUnit ] = .... and why are you trying to call it as a function in your h4? – GifCo May 21 '19 at 21:10
  • @DaminiGanesh In that case, what is `Unit.unit`, as it's not defined in that hook. – XCS May 21 '19 at 21:10
  • @GifCo I just have a

    Whole Building Water Flow ({waterUse.water_flow_unit})

    And its getting the data in the render just not converting the superscript
    – Damini Ganesh May 21 '19 at 21:10
  • Ok while the end of your question it says it outputs (G/ft²/yr) is that not what you want? – GifCo May 21 '19 at 21:11
  • @DaminiGanesh `⊃` is a HTML entity, you can't show plain HTML in React unless you use `dangerouslySetInnerHTML`. – XCS May 21 '19 at 21:11
  • @Cristy It is defined but there is more data I am setting using the hooks as an object which I can show so I am just should you the method I have used. The data in the hook is getting set and is being displayed. I just want it to convert the superscript while displaying – Damini Ganesh May 21 '19 at 21:12
  • 1
    Possible duplicate of [How to show html entity using React?](https://stackoverflow.com/questions/44116800/how-to-show-html-entity-using-react) – XCS May 21 '19 at 21:13

1 Answers1

0

The solution I found which worked best for me is

<span
 dangerouslySetInnerHTML={{
  __html: `${Unit.unit})`
   }}
 />

Make sure you out it in a span or a div element or else you ll get a -- Objects are not valid as a React child (found: object with keys {__html}). If you meant to render a collection of children, use an array instead-- error

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

Damini Ganesh
  • 288
  • 1
  • 10