简体   繁体   中英

Can you use jsx within template string in React render props?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM