I’m trying to implement simple conditional rendering where if prefixText prop has more than 0 string then render double span elements else render single span element. But on prefixText.length I get error message saying ", is expected". Also on Text, I get "missing properties for ReactElement<any, any>" type error. How can I fix this issue?
https://codesandbox.io/s/text-component-v2dbt?file=/src/App.tsx:0-538
import * as React from "react";
export interface TextProps {
children: string;
prefixText?: string;
}
export const Text: React.FunctionComponent<TextProps> = ({
children,
prefixText
}: TextProps) => {
return (
{ prefixText.length > 0 ?
<span>
<span style={{ fontWeight: "bold" }}>{prefixText} </span>
<span>{children}</span>
</span> :
<span>{children}</span>
}
);
};
export default function App() {
return (
<div>
<Text prefixText="Tips:">favourite vacation</Text>
</div>
);
}
>Solution :
Update your return block code to as follows:
return (
prefixText ?
<span>
<span style={{ fontWeight: "bold" }}>{prefixText}</span>
<span>{children}</span>
</span> :
<span>{children}</span>
);
Or update your component to the following:
export const Text: React.FunctionComponent<TextProps> = ({
children,
prefixText
}: TextProps) => (
prefixText ?
<span>
<span style={{ fontWeight: "bold" }}>{prefixText} </span>
<span>{children}</span>
</span> :
<span>{children}</span>
);