2
votes

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.

1
customText != null && customText.length > 0 && ... will return false if both conditions are not true. What happens if you write customText != null && customText.length > 0 ? <tr> ... </tr> : null instead?Tholle

1 Answers

2
votes

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