Home > Back-end >  How to return HTML in a Javascript/JSX function return?
How to return HTML in a Javascript/JSX function return?

Time:05-14

The following snippet will return and ordinal number if I leave the <sup> tags out. But I need them so that I can style it differently than the number itself. Right now it returns 1[Object Object], 2[Object Object]...n[Object Object]

const ordinal = (num) => {
  var j = num % 10,
      k = num % 100;
  if (j === 1 && k !== 11) {
      return num   (<sup>st</sup>);
  }
  if (j === 2 && k !== 12) {
      return num   (<sup>nd</sup>);
  }
  if (j === 3 && k !== 13) {
      return num   (<sup>rd</sup>);
  }
  return num   (<sup>th</sup>);
}

Thanks guys

CodePudding user response:

You appear to be returning JSX. In that case the entire response needs to be a JSX element. Not a number added to a JSX element (which itself is just an object, and adding a number to an object produces the output you're getting, since it's just trying to concatenate strings).

Something like this:

return <>{num}<sup>th</sup></>;

Or if empty fragments aren't supported:

return <React.Fragment>{num}<sup>th</sup></React.Fragment>;

Or perhaps wrap it in an element:

return <span>{num}<sup>th</sup></span>;

There are options. But the point is that you want to return a JSX element overall.

  • Related