Home > Mobile >  Render props with typescript
Render props with typescript

Time:05-20

I am trying to create a render props wrapper component. It is working, but I am getting type errors. Here is my link to a code sandbox as well. link to sandbox

  1. the first error I am getting is children is an expression that is not callable.
  2. the second error is "hello" has implicitly any type.

Looking for a react/typescript guru for help

type Props = {
  children: JSX.Element;
};


const ControlledWrapper: FC<Props> = ({ children }) => {
  const state: { hello: string } = { hello: 'hello' };

  return children(state);
};



export default function App() {
  return (
    <ControlledWrapper>
    {({ hello }) => <div>{hello}</div>}
  </ControlledWrapper>
  );
}

CodePudding user response:

Change the type of children to a function that returns a React element:

type Props = {
  children: (ctx: { hello: string }) => ReactElement;
};

Now when you use the component you get the right types:

    {({ hello }) => <div>{hello}</div>} // 'hello' is a string

Try this out here.

  • Related