46

I am wanting to show the 'cubic' html entity (superscript 3). I am doing like this:

const formatArea = function(val){
    return val + " ft³";
}

where formatArea is being called from inside the component':

render(){
    return (
        <div>
            {formatArea(this.props.area)}
        </div>
    );
}

but, the browser is showing it as ft&sup3;

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
JoeTidee
  • 24,754
  • 25
  • 104
  • 149

6 Answers6

41

Another option is to use fromCharCode method:

const formatArea = (val) => {
    return val + ' ft' + String.fromCharCode(179);
}
Avishay28
  • 2,288
  • 4
  • 25
  • 47
40

New way using React's fragments:

<>&sup3;</>

In your case it can be:

const formatArea = function(val){
    return <>{val + ' '}&sup3;</>
}
torvin
  • 6,515
  • 1
  • 37
  • 52
  • 1
    thx, you can also use this with the ternary operator e.g. `{ sortOrder === 'asc' ? <> ▲> : <> ▼> }` – wal Nov 16 '20 at 23:58
20

Found this way using JSX:

const formatArea = (val) => {
    return (<span>{val}&nbsp;ft<sup>3</sup></span>);
}
JoeTidee
  • 24,754
  • 25
  • 104
  • 149
17

You can get that using dangerouslySetInnerHTML feature of jsx.

Another way would be use correspond unicode character of html entity and just use as normal string.

const formatArea = function(val){
    return val + " ft&sup3;";
}

const Comp = ({text}) => (
<div>
<div dangerouslySetInnerHTML={{__html: `${text}`}} />
<div>{'53 ft\u00B3'}</div>
</div>

);

ReactDOM.render( <Comp text={formatArea(53)} /> ,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
WitVault
  • 23,445
  • 19
  • 103
  • 133
17
  • Method 1

    const formatArea = val => <div>{val} ft{'³'}</div>

  • Method 2

    const formatArea = val => <div>{val} ft{'\u00B3'}</div>

  • Method 3: fromCharCode

    const formatArea = val => <div>{val} ft{String.fromCharCode(parseInt('B3', 16))}</div>

  • Method 4

    const formatArea = val => <div>{val} ft{String.fromCharCode(179)}</div>

  • Method 5: HTML Codes

    const formatArea = val => <div>{val} ft&sup3;</div>

  • Method 6

    const formatArea = val => <div>{val} ft&#179;</div>

  • Method 7

    const formatArea = val => <div>{val} ft<sup>3</sup></div>

Then you can render it:

render() {
  return (
    {formatArea(this.props.area)}
  )
}
Yuci
  • 27,235
  • 10
  • 114
  • 113
  • This is a great answer, but the usage is odd. Since this is React wouldn't it make sense to render it as `` And declare those as proper components such as `const FormatArea = ({val})=>
    {val} ft{'³'}
    `
    – DiamondDrake Mar 22 '20 at 16:35
0
const formatArea = function(val){
  return <>{val} ft<span>&sup3;</span></>;
}

render(){
    return (
        <div>
            {formatArea(this.props.area)}
        </div>
    );
}

Demo

Ren Yun
  • 31
  • 2