Gerard
Gerard

Reputation: 63

Inject children into react component passed by props in TypeScript

I have a component where I want to append some stuff to the parent component passed by props. Something like:

function MyComponent(props : IMyProps) {
return ( {<props.parent>}{myStuff}{</props.parent>}
}

So I can call my new component like this:

<MyComponent parent={<h1 />} />

And MyComponent will append children to the h1 element. Can this be done?

Upvotes: 0

Views: 268

Answers (1)

Nick Vu
Nick Vu

Reputation: 15520

parent is already is a JSX, but your problem is you haven't passed children which is representing myStuff

Note that React's components are only callable with the first-letter-capitalized names, so I've assigned parent to Parent, and in the meanwhile, I've also added React.Fragment to prevent undefined-value cases from parent.

const MyComponent = ({ parent }) => {
   const Parent = parent || React.Fragment //convert it to a callable component
   const myStuff = "Testing" //simulating your stuff
   return <Parent>{myStuff}</Parent>
}

ReactDOM.render(
  <MyComponent parent={({children}) => <h1>{children}</h1>}/>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

If you only want to pass <h1/>, you need to clone the element and pass children in MyComponent by React.cloneElement

const MyComponent = ({ parent }) => {
   const myStuff = "Testing" //simulating your stuff
   return React.cloneElement(parent, {}, myStuff)
}

ReactDOM.render(
  <MyComponent parent={<h1/>}/>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 1

Related Questions