Home > front end >  Does React have something similar to Angular's *ngIf?
Does React have something similar to Angular's *ngIf?

Time:04-29

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.

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...?

CodePudding user response:

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