drewkiimon
drewkiimon

Reputation: 591

Typescript: Using boolean type is not accepted by TS compiler

Right now, I put isLoading to any, but if I put it to boolean (like I want it to be), it throws the following error when hovering over the "Loading" const. As far as I understand, this should be working. Very new to Typescript, so please be gentle. Any help would be appreciated.

package.json

"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"typescript": "^4.0.3"

Error message

Type '{ ({ isLoading, size, color, }: LoadingProps): false | JSX.Element; defaultProps: Partial<LoadingProps> | undefined; }' is not assignable to type 'FC<LoadingProps>'.
  Type 'false | Element' is not assignable to type 'ReactElement<any, any> | null'.
    Type 'false' is not assignable to type 'ReactElement<any, any> | null'.ts(2322)

index.tsx

import React from 'react';
import ClipLoader from 'react-spinners/ClipLoader';

interface LoadingProps {
  isLoading: any;
  size?: number;
  color?: string;
}

/**
 * Loading icon to let user know a promise is going on
 *
 * @param isLoading Passing true to show spinner, and pass false to remove it
 * @param size react-spinner parameter for size of icon
 * @param color Color of Loading icon
 */

const Loading: React.FC<LoadingProps> = ({
  isLoading,
  size = 35,
  color = '#F6F7FB',
}: LoadingProps) => {
  return isLoading && <ClipLoader size={size} color={color} />;
};

Loading.defaultProps = {
  size: 35,
  color: '#F6F7FB',
};

export default Loading;

Upvotes: 2

Views: 735

Answers (1)

Jordi Nebot
Jordi Nebot

Reputation: 3401

When isLoading is false your return statement returns false, which is not a ReactElement.

I'd suggest always using a ternary for conditional rendering instead. Like:

return isLoading ? <ClipLoader size={size} color={color} /> : null

See Conditional Rendering in docs for more details.

Upvotes: 4

Related Questions