2

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
  • 3
    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? Commented Jul 5, 2018 at 14:19

1 Answer 1

2

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
);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that seems to have worked. Is adding the ternary the only way to get around this? In our project, we're using a lot of React's conditional rendering using the && operator (e.g. someCheck && <someComponent>)
@noblerare I'm not sure to be honest. I have not found another way around it myself. I also like to use && when using React with just JavaScript, but haven't found a way to do it in TypeScript.

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.