Home > Mobile >  How to fix type issue for conditional rendering?
How to fix type issue for conditional rendering?

Time:02-15

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

CodePudding user response:

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

CodePudding user response:

You have to wrap your return statement into React.Fragment.

It should look like this

return (
  <>  
    { prefixText.length > 0 ? (
    
      <span>
        <span style={{ fontWeight: "bold" }}>{prefixText} </span>
        <span>{children}</span>
      </span> 
    ) : (
      <span>{children}</span>
    )
  </>  
}
);

Or you can also get rid of return braces and create a construction like this:

return prefixText.length > 0 ? (
        <span>
          <span style={{ fontWeight: "bold" }}>{prefixText} </span>
          <span>{children}</span>
        </span>
      ) : (
        <span>{children}</span>
      )

CodePudding user response:

wrap your component with react.fragment and also check if prefixText exist in your condition because prefixText is a partial in your typescript interface

return (
    <React.Fragment>
      { prefixText && prefixText.length > 0 ?
      <span>
        <span style={{ fontWeight: "bold" }}>{prefixText} </span>
        <span>{children}</span>
      </span> :
      <span>{children}</span>
    }
    </React.Fragment>
  );
  • Related