Components become useful building blocks of our app if we make them reusable. When we reuse components efficiently, we can avoid having to recreate parts of our app again and again. If you want to reuse a component in multiple places, you'll need a way to template out parts of it.
Let's start with two similar but not identical avatar components, that represent different users:
The structure of these components is identical, but they have somewhat
different content (the user's first initial) and attributes (the title
and class
attributes).
Arguments
We can create a component that can be used in both situations by templating the parts of the HTML that are different.
The syntax {{@initial}}
means that the contents inside the <div>
tag are
dynamic and will be specified by the <Avatar>
tag. Likewise, the
{{@title}}
syntax means that the contents of the title
attribute are dynamic
and will be specified in the same way. We can now replace the received message
avatar by using the <Avatar>
tag and providing it with some arguments.
This code includes the <Avatar>
component, which expects two arguments:
@title
and @initial
.
You are probably familiar with HTML attributes, which tell the browser how to
draw an HTML element. The syntax @title=
is similar, but instead of telling
the browser what to do, it's telling your custom tag what to do.
HTML Attributes
Let's try to use our <Avatar>
component for the sent message avatar.
We're really, really close.
We're just missing the current-user
class on the HTML <aside>
element. To
make that work, we'll specify the HTML attribute class
on the <Avatar>
tag.
The avatar component also needs to specify where to put attributes that were specified on the tag.
The ...attributes
syntax determines where the attributes from a tag should
appear in the component's template. Any number of attributes can be specified on
the avatar component now, and they will all end up on the element that has
...attributes
.