The methods used in the previous steps are great when working with a single iterable as a source of data but sometimes the situation might call for a more imperative approach.
In this example, the component has the following state properties:
friends - an array of strings.
pets - an array of objects.
includePets - a boolean controlled by a button.
Render a list item for each member but also include pets if includePets is true. The list item for the pet should include both the name and the species.
Populate the listItems array conditionally based on the boolean state, as shown below.
Then add the listItems array to your element's template.
// my-element.ts
render() {
⋮
returnhtml`
⋮
<ul>
${listItems}
</ul>
`;
}
// my-element.js
render() {
⋮
returnhtml`
⋮
<ul>
${listItems}
</ul>
`;
}
Click the button to see if the conditional rendering is working properly.
Extra Credit: Try refactoring the code to abstract the logic out of the render() method into its own private method that returns the array of templates. Then invoke the new method inside the template expression (replacing listItems).