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
Add a ment  | 

1 Answer 1

Reset to default 2
var 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