2
votes

Is it possible to put JSX inside a template string that is being used as a React render prop?

This is what I'm trying to do, but it leads to the link rendering as [object Object]

const Container = ({ message }) => <div className="from line 4"> {message}</div>;
const Link = () => <a href="#">juan</a>;

const App = () => (
  <div>
    <Container message={`My message with a ${<Link />}`} />
  </div>
);

One thing I tried was to put JSX instead of a template string inside message. This works, but it introduces a new div that isn't needed.

<Container
  message={<div>My message {<Link />}</div>}
/>

I made this codesandbox to illustrate the problem

1

1 Answers

6
votes

You can use a Fragment to render inline like you are trying to do and to prevent adding a new wrapping <div />:

const App = () => (
  <div>
    <Container
      message={<React.Fragment>My message with a <Link /></React.Fragment>}
    />
  </div>
);

Here is a forked version of your Codesandbox using React.Fragment: https://codesandbox.io/s/nrmr9l34vl