I'm building my first Ionic React app and created a simple custom component that returns content based on two optional input values.
When I had a simple if/else if/else conditional, the component rendered fine, but adding an extra 'else if' prevents it from compiling and I've not been able to establish why.
Here's the working component:
import React from 'react';
import './CardContainer.css';
interface ContainerProps {
position?: string;
content?: string;
}
const CardContainer: React.FC<ContainerProps> = ({ position = "right", content = "n/a"}) => {
let cardOutput;
if ( position.trim().toLowerCase() === "right" ) {
cardOutput = <><div className="ion-float-right">{content}</div><div className="clear-right"></div></>;
} else if ( position.trim().toLowerCase() === "left" ) {
cardOutput = <div className="ion-float-left">{content}</div>;
} else {
cardOutput = <div className="ion-float-left">{content}</div>;
}
return (
cardOutput
)
};
export default CardContainer;
And here is the code that won't compile:
import React from 'react';
import './CardContainer.css';
interface ContainerProps {
position?: string;
content?: string;
}
const CardContainer: React.FC<ContainerProps> = ({ position = "right", content = "n/a"}) => {
let cardOutput;
if ( position.trim().toLowerCase() === "right" ) {
cardOutput = <><div className="ion-float-right">{content}</div><div className="clear-right"></div></>;
} else if ( position.trim().toLowerCase() === "left" ) {
cardOutput = <div className="ion-float-left">{content}</div>;
} else if ( position.trim().toLowerCase() === "empty" ) {
cardOutput = <div className="ion-padding-top">{content}</div>;
}
return (
cardOutput
)
};
export default CardContainer;
The only significant difference is that I've replaced the 'else' condition with an 'else if'. I've tried adding in an 'else' condition just to eliminate possible cause and this as expected doesn't fix the issue.
When I try and run the app on my dev system I get this output:
Type '({ position, content }: PropsWithChildren) => Element | undefined' is not assignable to type 'FC'. Type 'Element | undefined' is not assignable to type 'ReactElement<any, any> | null'. Type 'undefined' is not assignable to type 'ReactElement<any, any> | null'.ts(2322)
To my inexperienced eye this doesn't give me much indication of what the issue is beyond it relating to TypeScript.
This is because your data may lie in the if conditions and thus the variable declared cardoutput is still undefined.
let cardOutput;//undefined
So try to use an else condition so that the cardoutput wont be undefined