There are so many ways you could organize a program to render things to the DOM. But here’s a little work-through considering your choices and different patterns you could use.
There’s a reason hundreds of devs work for years to build out UI libraries and JS frameworks. And a lot of things to consider. But for now, keep it simple and fun!
Here’s the basic procedure.
But then it just goes and you have no way to control it or reuse it.
Wrapping that in a function gives you control (and encapsulation)
The template might get a little more complex. You can format it to make it a bit more readable. But what if you have a nested list or something? It could get weird and you don’t have syntax highlighting and you could make more mistakes.
Here’s a shorthand for tacking the new string to the base string. (for some people, this is more or less readable)
If you’re going to use it – make sure you’re 100% clear on what it does, and you didn’t just memorize it and create a bad conceptual model.
You can break the single item out into it’s own function. This will keep things more readable and give the function a smaller scope to handle. Depending on your situation, this might be more or less readable. So, it’s up to you to figure that out.
People tend to get sick of writing out the
template (or whatever you call it) (the variable for the base string) – and they’ll see this trick using
Array.map() and adopt it. But if it’s too tricky, just use the
Array.forEach() style until you change your mind.
The array method
map is creating an array based on what you give it, so something like
["<li>a</li>","<li>b</li>","<li>c</li>"] and the
Array.join('') is putting the array back together as a string – and instead of a comma, using a nothing to connect them into their final output `
Kinda weird at first! And not as readable for new people. (but faster to write in some situations)
Some of these functions aren’t really rendering anything. They’re just returning a value (a string representing some HTML markup);
Maybe naming them differently will be helpful to differentiate them.
You could have a generic render function like this.
You need to know what to render – but also, where to render that. You can use a default parameter value (a pretty good example of a use-case for that if you haven’t used them yet)
You can build out some JS-based list of stuff! And now that you have a function to render items, you can decide what items it renders. What if you want to filter the item by category? You could click a button (maybe get the category name from a data-attrubute?) and then use that to filter the item list and render the filtered list. By combining what you know about events and arrays and string templates – you can do a lot of stuff.