noblerare
noblerare

Reputation: 11943

Typescript - Error when importing React functional component

I am migrating my React .js files to .tsx files and stumbled upon this issue. Here is a bare-bone example of the problem.

ParentComponent.tsx

import MyCustomComponent from './MyCustomComponent';

export class ParentComponent extends React.Component<{customText: string}> {
    render() {
        return (
            <MyCustomComponent customText={this.props.customText} />
        );
    }
}

MyCustomComponent.tsx

export const MyCustomComponent = ({ customText }: { customText : string }) => (
    customText != null && customText.length > 0 &&
    <tr>
        <td colSpan={12} className={"somecssclass"}>
            <div className={"somecssclass2"}>
                {customText}
            </div>
        </td>
    </tr>
);

There is a red underline on the <MyCustomComponent ... /> line with the following errors:

ERROR in [at-loader] ./src/app/MyComponent.tsx:78:37 TS2605: JSX element type 'false | Element' is not a constructor function for JSX elements. Type 'false' is not assignable to type 'ElementClass'.

ERROR in [at-loader] ./src/app/MyComponent.tsx:78:37 TS2607: JSX element class does not support attributes because it does not have a 'props' property.

ERROR in [at-loader] ./src/app/MyComponent.tsx:78:52 TS2339: Property 'customText' does not exist on type '{}'.

Any help would be greatly appreciated.

Upvotes: 2

Views: 2555

Answers (1)

Tholle
Tholle

Reputation: 112927

customText != null && customText.length > 0 && ... will return false if both conditions are not true, which TypeScript interprets as invalid JSX.

You can instead explicitly return null if both conditions are not true, and it will work:

export const MyCustomComponent = ({ customText }: { customText: string }) => (
  customText != null && customText.length > 0 ? (
    <tr>
      <td colSpan={12} className={"somecssclass"}>
        <div className={"somecssclass2"}>{customText}</div>
      </td>
    </tr>
  ) : null
);

Upvotes: 2

Related Questions