Listing 3-9: Conditional Rendering with Element Variables
import Header from './Header';
import Login from './Login';
function Welcome({loggedIn}) {
let header;
if (loggedIn) {
header = <Header />;
} else {
header = <Login />;
}
return (
<div>
{header}
</div>
)
}
export default Welcome;
Conditional Rendering with Element Variables
Outside of the return statement, create a variable to hold the element you want to render conditionally. You can then use an if/else statement to assign different elements to the variable based on any condition. In this example, the Boolean isLoggedIn
is passed to the component as a prop and a different component is assigned to the header
variable based on whether isLoggedIn
is true or false. The final step is to render the header
variable inside the return statement.
The benefit of using this method for conditional rendering is that it's easy to read, and you can have as many branches as you need.
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.