Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Render props with typescript

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>
  );
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading