javascript - Display React component only when attribute is not null - Stack Overflow

MyReactComponent returns a hyperlink and a message after looking up an API using the name value. Howeve

MyReactComponent returns a hyperlink and a message after looking up an API using the name value. However I would like to render this ponent (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>

MyReactComponent returns a hyperlink and a message after looking up an API using the name value. However I would like to render this ponent (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>
Share Improve this question edited Jul 11, 2022 at 22:01 dippas 60.6k15 gold badges123 silver badges132 bronze badges asked Jul 11, 2022 at 21:43 Punter VickyPunter Vicky 17.1k62 gold badges213 silver badges341 bronze badges 1
  • 2 {name && name.trim() !== "" && <MyReactComponent />}, so in the case MyReactComponent will be rendered if name has some value – user13937286 Commented Jul 11, 2022 at 21:46
Add a ment  | 

2 Answers 2

Reset to default 5

Here is another way you can do this :

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

You can learn more here.

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744184449a4562138.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信