Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if react element is 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?

like image 602
Alexander Schranz Avatar asked Oct 19 '15 16:10

Alexander Schranz


1 Answers

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 component at all, then that should happen in the parent.

like image 103
Dominic Avatar answered Oct 17 '22 01:10

Dominic