Search code examples
reactjstypescriptcompiler-errorschildren

Getting error when using type "React.ReactNode" to children. Which type should I use?


Getting error message when using function LoaderIndicator(), which renders children, when loading = false, see code below. The error appeared when I used React.ReactNode instead of type any, but normally I use React.ReactNode as type for children. This is the error I get:

'LoaderIndicator' cannot be used as a JSX component. Its return type '{}' is not a valid JSX element. Type '{}' is missing the following properties from type 'Element': type, props, key. ts(2786)

I don't know how to fix this error, I have tried almost everything, is anyone able to help? :)

export type LoaderIndicatorProps = {
  loading: boolean;
  children?: React.ReactNode; 
};
export function LoaderIndicator(props: LoaderIndicatorProps) {
  const { loading, children } = props;

  if (loading) {
    return (
      <div>
        <Container>
          <Icon />
          <h3 style={{ color: "#ffffff" }}>Wait for a moment...</h3>
        </Container>
      </div>
    );
  } else {
    return children;
  }
}

Solution

  • React components should return JSX.Element. As you can see, your children are of type React.ReactNode, so straight returning them will not work. You need to wrap them inside an element or React.Fragment:

    type TestComponentProps = {
        children?: React.ReactNode;
    }
    
    function TestComponent(props: TestComponentProps) {
        return <React.Fragment>{props.children}</React.Fragment>;
    }