Passing non-string data to dependent child components #14
-
I often have cases like this:
Or
What I want is for the child thing to have access to some nested state object from the parent - otherwise the parent has to do something hideous like I successfully achieved the first example on one project by giving the parent element a reference to the child element, from the child's onConnect(), then letting the parent call methods on the child directly to provide data objects. I've tried to boil this down here:
It would be nice if I could simply do something like html Is there a better way? I also tried having the child's connectedCallback call a method on the parent to get its data, but this caused infinite recusion errors. The other error I get is "The value of type [object HTMLElement] is not allowed in observables." (I hit this because I'm now trying to do a hierarchical/recusive treeview with cami.js but I'm interested in discussing the concept at a simpler level first). |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Hi @artfulrobot ! What I do in that case is that I use the dot syntax. What that dot essentially does is set a value to a reactive property. Here's an example: // Instead of this (which would stringify):
html`<my-thing thingData=${this.appData.a}></my-thing>`
// Do this (note the dot before thingData):
html`<my-thing .thingData=${this.appData.a}></my-thing>` From an example in a real world app I've been working on: // Simple parent component
class ChatList extends ReactiveElement {
messages = [
{ id: 1, text: "Hello", type: "user" },
{ id: 2, text: "Hi there!", type: "ai" }
];
template() {
return html`
${this.messages.map(message => html`
<chat-message
.messageData=${message}
></chat-message>
`)}
`;
}
}
// Simple child component
class ChatMessage extends ReactiveElement {
connectedCallback() {
super.connectedCallback();
// Declare what properties we expect from parent
this.warnIfMissingProperties(["messageData"]);
}
template() {
// Access the property directly
const { text, type } = this.messageData;
return html`
<div class="message ${type}">
${text}
</div>
`;
}
}
customElements.define("chat-list", ChatList);
customElements.define("chat-message", ChatMessage); |
Beta Was this translation helpful? Give feedback.
-
The docs certainly miss this -- there is an upcoming release soon which will also cover that. The release is currently driven by a production app -- once the release there is done, v0.4.0 will follow soon (with some new conventions based on what I've learned so far from using Cami in that codebase). |
Beta Was this translation helpful? Give feedback.
Hi @artfulrobot !
What I do in that case is that I use the dot syntax. What that dot essentially does is set a value to a reactive property. Here's an example:
From an example in a real world app I've been working on: