Check out myAngular article series with live demos and Facebook group Angular - Advanced Topics

Hiding and showing elements in React

Torgeir "Tor" Helgevold
- JavaScript Developer and Blogger
Published: Sun Feb 22 2015

In the following post I will demonstrate how to conditionally render content in a React component.

One thing I really like about React is how easy and intuitive it is to define components using declarative syntax in tandem with plain JavaScript logic. A React render method typically consists of some control flow leading up to a returned JSX body. The returned JSX element is dynamic and will react to values defined in plain JavaScript code.

The following is an example of a simple component that renders one of two greetings based on a simple property value.

Option 1 hide/show by conditional rendering

var Greeting = React.createClass({ render:function(){ var partial; if(this.props.gender === "male"){ partial = <div>Hello Mr. Jones</div> } else{ partial = <div>Hello Mrs. Jones</div> } return ( <div> <div>Greeting</div> {partial} </div> ); } });

Option 2 hide/show using css

var Greeting = React.createClass({ render:function(){ var classMale = ""; var classFemale = ""; if(this.props.gender === "male"){ classFemale = "displayNone"; } else{ classMale = "displayNone"; } return ( <div> <div>Greeting</div> <div className={classFemale}>Hello Mrs. Jones</div> <div className={classMale}>Hello Mr. Jones</div> </div> ); } });

Usage of the component:

<Greeting gender="male"></Greeting> <Greeting gender="female"></Greeting>

Option 1 and Option 2 will produce similar results, but there is an important difference. Option 2 uses css to hide or show the elements which means both greetings are physically present in the DOM at all times. Option 1 on the other hand will only create DOM elements for the visible greeting.

If you liked this article, share it with your friends on social media:

We also have a new Facebook group about advanced Angular topics.

I invite you to follow me on twitter