admin管理员组文章数量:1287506
I don't want to render the title when description is empty
var description = <MyElement />; // render will return nothing in render in some cases
if (!description) { // this will not work because its an object (reactelement)
return null;
}
<div>
{title}
{description}
</div>
Whats the correct way instead of !description to check if its empty?
I don't want to render the title when description is empty
var description = <MyElement />; // render will return nothing in render in some cases
if (!description) { // this will not work because its an object (reactelement)
return null;
}
<div>
{title}
{description}
</div>
Whats the correct way instead of !description to check if its empty?
Share Improve this question edited Jan 30, 2016 at 12:22 Dmitry Shvedov 3,2964 gold badges40 silver badges56 bronze badges asked Oct 19, 2015 at 16:25 Alexander SchranzAlexander Schranz 2,4583 gold badges26 silver badges43 bronze badges 2- Do you have any state/props that you can check to see whether description should be empty? It is better to do the check using these, rather than inspecting an element's children. – J3Y Commented Oct 19, 2015 at 18:19
- No not really the data is build by some props which are converted/filtered in the myelement ponent. If there is no way I need to move this Logik to the parent ponent. Then I could check in this props. – Alexander Schranz Commented Oct 19, 2015 at 18:26
1 Answer
Reset to default 2var description, title;
if (this.props.description) {
description = <Description description={this.props.description} />;
if (this.props.title) {
title = <Title title={this.props.title} />;
}
}
<div>
{title}
{description}
</div>
Or:
render() {
const { description, title } = this.props;
return (
<div>
{title && description && <Title title={title} />}
{description && <Description description={description} />}
</div>
);
}
Imo it's better practice that if your description element isn't needed then it isn't rendered, rather than returning null in it's render. Since you would likely be sending the data through a prop. And likewise if you don't want to render this ponent at all, then that should happen in the parent.
本文标签: javascriptCheck if react element is emptyStack Overflow
版权声明:本文标题:javascript - Check if react element is empty - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741260585a2367543.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论