Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is proper type for React's children as function?

I'm passing a children as a function, returning React.ReactNode into Provider HOC like follows:

<Provider variables={{ id: "qwerty" }}>
  {data => (
    <ExampleComponent data={data} />
  )}
</Provider>

Here's a provider component example code:

type Props = {
  id: string;
  children: any; // What type should be put here?
};

const Provider: React.SFC<Props> = ({ id, children }) => {
  const { data, loading, error } = useQuery<req, reqVariables>(query, {
    variables: { id }
  });

  if (loading) return "Loading...";
  if (error) return "Error";
  if (!data) return "No data";

  return children(data);
}

If I'm not specifying any type for children, so leaving it to default to React.ReactNode, then line return children(data); shows an error:

Cannot invoke an expression whose type lacks a call signature. Type 'string | number | boolean | {} | ReactElement ReactElement Component)> | null) | (new (props: any) => Component)> | ReactNodeArray | ReactPortal' has no compatible call signatures.

If I'm specifying children explicitly in type Props as any, everything works great, but it's Wrong from a Typescript and types perspective.

What is a proper type to be put for props.children, when a function returning React.ReactNode is passed instead of React.ReactNode itself, so Typescript would accept it as a valid "Render function" and will allow calling children like function?

like image 658
Kamilius Avatar asked Oct 15 '25 17:10

Kamilius


1 Answers

You can specify the children type to be a function which returns a ReactNode

type Props = {
  id: string,
  children: (props: InjectedCounterProps) => React.ReactNode
};
like image 193
Shubham Khatri Avatar answered Oct 17 '25 11:10

Shubham Khatri