Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

ReactJS

How to use React children prop in Typescript

How to use children prop in react typescript app

First you can create a interface to specify the props needed in the component. Then you can extends that interface from React.PropsWithChildren which contain children prop.

import React from 'react'

interface props extends React.PropsWithChildren {
    name?:string
}

function CustomComponent({children}:props) {
  return (
    <>
     <p>Inside Component</p>
     <div>{children}</div>    
    </>
  )
}

export default CustomComponent

You can use the component like below in the application. The content under the CustomComponent will be rendered inside the div which is specified the children prop.

<CustomComponent>
   <p>Inside Main App 1</p>
   <p>Inside Main App 2</p>
</CustomComponent>