[React x TypeScript] How to pass components as Props

TiShow
Aug 11, 2022

tips

  1. Use JSX.Element, React.ReactNode, etc. for the specified Props type.
  2. When it receives the components, receive props as an argument and extract the component from props. When creating a function component, props are often written as ({child1, child2}) etc. in the argument, but it should be (props) (probably because of rendering).
https://unsplash.com/photos/UYsBCu9RP3Y

Code

Suppose a components called Children receives the components with props names child1 and child2.

import React from 'react'

type Props = {
child1: JSX.Element
child2: JSX.Element
}

export default Children: React.FC<Props> = (props) => {
const { child1, child2 } = props

return (
<div>
{child1}
<div>{child2}</div>
</div>
)
}

When the Children component is used, specify each prop as usual.

import React from 'react'

export default Parent: React.FC = () => {
return (
<Children
child1 = {<div>child1</div>}
child2 = {<div>child2</div>}
/>
)
}

Happy coding !

--

--

TiShow

80% is the creation, the rest is depression. Developer and Data scientist. Looking for Physics Ph.D Twitter: @_t_i_show