Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 849
Jessie Emerson Avatar asked Dec 20 '16 16:12

Jessie Emerson


People also ask

How do I hide a selected element in HTML?

The hide () method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show () method.

What is the difference between show and hide in CSS?

The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show() method.

How do I use if statements outside of my JSX?

If a ternary expression isn't robust enough, you can use if statements outside of your JSX to determine which components should be used: Or if you prefer a more "inline" aesthetic, define immediately-invoked function expressions inside your JSX: In the example above, an ES6 arrow function is utilized to lexically bind the value of this.

What is the use of hide method in HTML?

Definition and Usage. The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page).


2 Answers

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}
  )
}
like image 66
taylorc93 Avatar answered Sep 19 '22 16:09

taylorc93


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>
    );
}
like image 28
Ori Drori Avatar answered Sep 17 '22 16:09

Ori Drori