Jessie Emerson
Jessie Emerson

Reputation: 743

jsx if else shorthand to hide element

I can do

<p>Company: {{this.state.user.company}}</p>

but sometime company has no value. So how should I hide the entire

if the property of company is null?

I tried

<p>({this.state.user.company} ? 'Company: ' + {this.state.user.company} : '')</p>

But it doesn't work.

Upvotes: 9

Views: 14908

Answers (4)

undefined
undefined

Reputation: 2491

You could also use the following for a short handed format:

render() {
  return (
    {this.state.user.company ?? <p>Company: {this.state.user.company}</p>}
  )
}

Reference Nullish coalescing operator (??)

Upvotes: 0

GG.
GG.

Reputation: 21844

Another alternative:

render() {
  if (!this.state.user.company) return (<p>Loading...</p>)

  return (
    <div>
      <p>Name: {this.state.user.company.name}</p>
      <p>Address: {this.state.user.company.address}</p>
      <p>Creation date: {this.state.user.company.creation}</p>
    </div>
  )
}

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191976

React doesn't render falsy values, so you can use short-circuit evaluation. If this.state.user.company is null, it will be ignored by react. If it's truthy, react will render the element after &&.

render() {
    return (
        <div>
        {this.state.user.company &&
            <p>Company: {this.state.user.company}</p>
        }
        </div>
    );
}

Upvotes: 9

taylorc93
taylorc93

Reputation: 3716

Alternative syntax to Ori Drori's answer (I find this a bit easier to read):

render() {
  return (
    {this.state.user.company ? <p>Company: {this.state.user.company}</p> : null}
  )
}

Upvotes: 8

Related Questions