Search code examples
javascriptreactjstemplate-strings

Passing template literal as prop is not rendering


I've got a functional component

const Paragraph = forwardRef((ref: any) => {
  return (
    <div>
      <p dangerouslySetInnerHTML={{ __html: props.text }}></p>
    </div>
  );
});

When I call this component I can't render this template literal:

<Paragraph text={`${<a href="#">Terms of Service</a>} and ${<a href="#">Privacy Policy</a>}`} />

the result is: [object Object] and [object Object]


Solution

  • The ES6 template literals takes expressions inside ${} that it converts to strings. You are giving it JSX objects ${<a href="#">Terms of Service</a>} which can't really be converted to a string representation, the best it can do is [object Object].

    What you really want is to set the inner HTML the the actual string <a href="#">Terms of Service</a>, so simply removing the ${} around your tags will give you the expected result.

    <Paragraph text={`<a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a>`} />