Home > Software design >  Display React component only when attribute is not null
Display React component only when attribute is not null

Time:07-12

MyReactComponent returns a hyperlink and a message after looking up an API using the name value. However I would like to render this component (which includes making the API call) only when name is not empty. Would the below solve the purpose or should I approach this differently?

   <dt hidden={null == name || '' === name.trim()}>
      <MyReactComponent name={name || ' '} />
    </dt>

CodePudding user response:

Here is another way you can do this :

{(name && name.trim() !== '') &&
    <MyReactComponent name={name} />
}

You can learn more here.

CodePudding user response:

Instead of using hidden attribute, you can render your component with ternary operator:

{name ? <MyReactComponent name={name} /> : null}
  • Related