React rendering raw HTML code instead of interpreting it

React rendering raw HTML code instead of interpreting it
0

#1

I have a function that returns a string of a number of divs equal to the number passed to it. When I call the function in my component it just shows the string of HTML code instead of interpreting it. I tried writing a div outside of the curly braces to see how it would evaluate. It makes the blue square at the bottom of the upper left square, so that works. Any ideas why the string returned from my function is not showing as intended?

const drawHpBar=function(hp){
  let hpBars = "";
  for(let i=0;i<hp;i++){
    hpBars = hpBars + '<div className="hpTick" id='+'"'+i+'"'+'></div>'
  }
  return hpBars;
}

class CharPic extends Component {
  render() {
    const hp=this.props.hp;
    return (
      <div className="menuBox" id="charPic">
        CharPic HP{this.props.hp}
        <br/>
        <div className="hpBar">
        {drawHpBar(hp)}
        </div>
        <div className="hpTick"/>
      </div>
    );
  }
}

Screenshot:


#2

I am not an expert in React but this post seems relevant.


#3

You don’t need to return a string, returning an array of JSX elements will do the trick. You are using Javascript Syntax Extension(JSX), not HTML.
We can store JSX elements in JavaScript variables and store them in array.

let arrUsers = [<li>Abdul Moiz</li>,<li>John Doe</li>]
<ul>
  {arrUsers}
</ul>

Above code will render a list of two users, Abdul Moiz and John Doe.
Following edits in drawHpBar should solve the problem for you.

const drawHpBar=function(hp){
  let result = [];
  for(let i=0;i<hp;i++){
    result.push(<div className="hpTick" id={i.toString()}></div>);
  }
  return result;
}

#4

Thank you, it works! It is my first time making my own react app without following along with someone on YouTube and I forgot about this detail how it is not exactly HTML.


#5

No problem, it takes some time to wrap your head around JSX, practice will make it easy for you. And at the end its the part of learning…:slight_smile: