What is Conditional Rendering?
- Ternary operation
- Inline IF with Logical && operator
- Switch case operator
In this blog, we will be adding conditional rendering to the React App example from my previous blog, Build a Search Bar in React.js. We will be focusing on using the if/else statement and ternary operator. Below is the revised code to my React App as well as the FlowerForm component code.
In the code above, I included a view state with a value of “false” as well as a viewForm function and a cancel function. The viewForm and cancel functions changes the state of view as soon as they are triggered which then changes the appearance of the app. When the “Add New Flower” button is clicked, the viewForm function is triggered and the FlowerForm appears. When the “cancel” button in the FlowerForm component is clicked, the cancel function is triggered, the FlowerForm disappears, and the webpage returns to its original appearance.
Below is how the code will look using an if/else statement. The if/else statement can be used in render() and should not be used inside a return statement and JSX. In order to keep everything in the same <div> or on the same webpage, the renderContent function was created to contain the if/else statement which can now be passed in the return statement in render().