Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix type issue for conditional rendering?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading