How to show html object using React?

I want to show a "cubic" html object (superscript 3). I do like this:

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

where formatAreacalled from inside the component:

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

but the browser shows it as ft&sup3;

+10
source share
4 answers

Found this method using JSX:

const formatArea = (val) => {
    return (<span>{val}&nbsp;ft<sup>3</sup></span>);
}
+8
source

Another option is to use the fromCharCode method :

const formatArea = function(val){
    return val + ' ft' + String.fromCharCode(179);
}
+10
source

, dangerouslySetInnerHTML jsx.

unicode html- .

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>
Hide result
+7
  • 1

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

  • 2

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

  • 3: CharCode

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

  • 4

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

  • 5: HTML-

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

  • 6

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

  • 7

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

:

render() {
  return (
    {formatArea(this.props.area)}
  )
}
0

Source: https://habr.com/ru/post/1677702/


All Articles