Skip to main content

Children


Properply typing children

JSX.Element

Children must be a single JSX element. Doesn't allow multiple children, or strings etc.

type ButtonProps = {
children: JSX.Element
}
const Button = ({children}: ButtonProps) => <button>{children}</button>

export function Card() {
return (
<Button>
<span>Click me</span>
</Button>
)
}

JSX.Element[]

Allows multiple JSX elements but no strings, numbers etc

type ButtonProps = {
children: JSX.Element[]
}
const Button = ({children}: ButtonProps) => <button>{children}</button>

export default function Card() {
return (
<Button>
<span>click me</span>
<i>svg icon</i>
</Button>
)
}

JSX.Element | JSX.Element[]

Allows single or multiple JSX elements but no strings, numbers etc

type ButtonProps = {
children: JSX.Element | JSX.Element[]
}
const Button = ({children}: ButtonProps) => <button>{children}</button>

export default function Card() {
return (
<Button>
<span>click me</span>
</Button>
)
}
export default function Card2() {
return (
<Button>
<span>click me</span>
<i>svg icon</i>
</Button>
)
}

React.ReactChild

Allows one React element, string or number

type ButtonProps = {
children: React.ReactChild
}
const Button = ({children}: ButtonProps) => <button>{children}</button>

export default function Card() {
return <Button>click me</Button>
}

React.ReactChild[]

Allows multiple React elements, strings or numbers

type ButtonProps = {
children: React.ReactChild
}
const Button = ({children}: ButtonProps) => <button>{children}</button>

export default function Card() {
return (
<Button>
click me
<i>svg icon</i>
</Button>
)
}

React.ReactChild | React.ReactChild[]

Allows single or multiple React elements, strings or numbers

type ButtonProps = {
children: React.ReactChild
}
const Button = ({children}: ButtonProps) => <button>{children}</button>

export default function Card() {
return <Button>click me</Button>
}

export default function Card2() {
return (
<Button>
click me
<i>svg icon</i>
</Button>
)
}

React.ReactNode

Allows multiple children, strings, numbers, fragments, portals... We could use the above example but it is a little verbose and ReactNode covers a little more.

type ButtonProps = {
children: React.ReactNode
}
const Button = ({children}: ButtonProps) => <button>{children}</button>

export default function Card() {
return (
<Button>
click me
<i>svg icon</i>
</Button>
)
}