5

I have a React component that takes children.

Getting a Typescript error:

Property 'children' is missing in type ... but required in type 'FixedWidthLayout'

That component is defined like a function statement.

export default function FixedWidthLayout { ... }

I don't want to write it like and expression..

i.e.

export const FixedWidthLayout = () => {...}

Therefore doing something like ...

const FixedWidthLayout: React.FC<Props> = () => {...}

..is not an option.

How is it possible to make this work with in Typescript with a function statement?

2 Answers 2

7

You can use React.PropsWithChildren, which will take a type argument for the props that you want to pass to the component other than the children. The return type for the component can be React.ReactNode.

interface IProps {
  // props you want to pass to the component other than the children
}

export default function FixedWidthLayout(props: React.PropsWithChildren<IProps>): React.ReactNode {

  return (
    <div>
      {props.children}
      {/*The jsx code for the component*/}
    </div>
  )

}
Sign up to request clarification or add additional context in comments.

1 Comment

If you don't care to type the other props, this works React.PropsWithChildren<any>.
1

Where are you getting the error?

This should just work:

import * as React from 'react';

interface Props {
  children: React.Node;
}

export default function FixedWidthLayout(props: Props): JSX.Element {
  /* ... */
}

<FixedWidthLayout>Hello</FixedWidthLayout>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.