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

Does React have something similar to Angular's *ngIf?

I trying to create a React component based on styled components. So far it looks something like this:

import { StyledComponent } from "./styles";

type ComponentProps = {
  icon: string;
  boldTxt?: string;
  normalTxt?: string;
};

const Component = ({ icon, boldTxt, normalTxt }: ComponentProps) => {
  return (
    <StyledComponent>
      <i className={icon}></i>
      <span>{boldTxt}</span>
      <span>{normalTxt}</span>
    </StyledComponent>
  );
};

export default Component;

In this case the content of the StyledComponent doesn’t matter.

Since the boldTxt and normalTxt props are optional it’s not always certain that there will be something in the spans. However, they will take up space even though they have no content.

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

In Angular I would just write something like:

<span *ngIf="boldTxt">{boldTxt}</span>
<span *ngIf="normalTxt">{normalTxt}</span>

And then the spans will only be rendered if they are not empty/null. Can this be achieved as elegantly in React, or…?

>Solution :

Nothing exactly like that, with an attribute. But perhaps:

const Component = ({ icon, boldTxt, normalTxt }: ComponentProps) => {
  return (
    <StyledComponent>
      <i className={icon}></i>
      {boldTxt && <span>{boldTxt}</span>}
      {normalTxt && <span>{normalTxt}</span>}
    </StyledComponent>
  );
};
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