Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'Element | undefined' is not assignable to type 'ReactElement<any, string | ((props: any)

I have a component that looks like this. This version works perfectly:

export default function StatusMessage(isAdded: boolean, errorMessage: string) {
  if (isAdded) {
    return <ResultAlert severity="success" text="User Added" />;
  } else {
    if (errorMessage !== '') {
      if (
        errorMessage.includes('email')
      ) {
        return <ResultAlert severity="error" />;
      }
      if (
        errorMessage.includes('phone number')
      ) {
        return (
          <ResultAlert severity="error" text="" />
        );
      } 
    }
  }
}

Now, I am trying to change the way I export it. I am trying this:

type StatusMessageProps = {
  isAdded: boolean; 
  errorMessage: string;
}

export const StatusMessage: React.FunctionComponent<StatusMessageProps> = ({
  isAdded,
  errorMessage
}) => {

but i keep getting an error that:

Type '({ isAdded, errorMessage }: PropsWithChildren<StatusMessageProps>) => Element | undefined' is not assignable to type 'FunctionComponent<StatusMessageProps>'.
  Type 'Element | undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
    Type 'undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
I am using the same method on different pages but the error is only here

Edit:

I am using this component like this:

 const [isAdded, setIsAdded] = useState(false);

{isSubmitted && StatusMessage(isAdded, errorMessage)}

it gives me an error on isAdded that

Argument of type 'boolean' is not assignable to parameter of type 'PropsWithChildren<StatusMessageProps>'.ts(2345)
like image 411
Jnl Avatar asked Jul 28 '20 10:07

Jnl


1 Answers

You must have forgotten return a value in your component. Are you forgetting return null since void 0 is unacceptable result of a React component?

export const StatusMessage: React.FunctionComponent<StatusMessageProps> = ({
  isAdded,
  errorMessage
}) => {
  if (isAdded) {
    return <ResultAlert severity="success" text="User Added" />;
  } else {
    if (errorMessage !== '') {
      if (
        errorMessage.includes('email')
      ) {
        return <ResultAlert severity="error" />;
      }
      if (
        errorMessage.includes('phone number')
      ) {
        return (
          <ResultAlert severity="error" text="" />
        );
      } 
    }

    // Here where you missed
    return null;
  }
}
like image 156
tmhao2005 Avatar answered Sep 28 '22 04:09

tmhao2005