Home > Software design >  Correct type for children props in wrapper class?
Correct type for children props in wrapper class?

Time:01-21

Im trying to create a wrapper class that simply returns children props

type Props {
  children: any;
}

const Wrapper: = ({ children }: Props) {
  //some logic

  return children;
}

Curios if it exist a more specific type than any for this purpose? If i try something like ReactNode or JSX.Element i can no longer pass multiple children. On the other hand by using a fragment, the linter complains because children may also be a single element.

const Wrapper: React.FC = ({ children }) =>  {
  return <>{children}</>;
}

Any thought appreciated!

CodePudding user response:

You can cast the children prop to a type that satisfies the return type of React.FC

const Wrapper: React.FC = ({ children }) =>  {
  return children as React.ReactElement;
}

CodePudding user response:

React.ReactNode is the correct type of the children prop of React components. And React components must return a JSX.Element.

These are not the same type.

children may be a list, and react components must return a single node. So you just have to wrap children in a fragment to guarantee you always get a single JSX.Element.

type Props = {
  children: React.ReactNode;
}

const Wrapper = ({ children }: Props) => {
  //some logic

  return <>{children}</>;
}

// works
const test1 = <Wrapper>123</Wrapper>
const test2 = <Wrapper>
  <>foo</>
  <>bar</>
</Wrapper>

Playground

  •  Tags:  
  • Related