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
Option 2 hide/show using css
Usage of the component:
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.