Issue
I have this code:
class Category {
constructor(
readonly _title: string,
) { }
get title() {
return this._title
}
}
const categories = {
get pets() {
const pets = new Category('Pets')
return {
get dishes() {
const dishes = new Category('Dishes')
return dishes
}
}
},
get cloth() {
const cloth = new Category('Cloth')
return {
get accessories() {
const accessories = new Category('Accessories')
return accessories
}
}
}
}
I want to use it like this
const product = new Product(categories.pets.dishes)
Its pretty good, but on frontend I should render this like tree:
<ul>
{Object.entries(categories).map(
([slug, category]) => {
return (
<React.Fragment key={slug}>
<li>{category.title}</li> // problem here
<ul>
{Object.entries(category).map(([s, c]) => {
return <li key={s}>{c.title}</li>
})}
</ul>
</React.Fragment>
)
})}
</ul>
How can I get the name of the parent category? What's the best way to design this?
Solution
The main problem is that in categories.pets
you create an instance pets
, but then do nothing with it. It is lost in oblivion. Instead you create another object by using an object literal (that is not an instance of Category
) and return that. Obviously that object does not have a title
...
For this to work, add the dishes
getter to the pets
object you just created, like so:
get pets() {
const pets = new Category('Pets');
Object.defineProperty(pets, "dishes", {
get() {
const dishes = new Category('Dishes');
return dishes
},
enumerable: true,
configurable: true,
});
return pets;
},
Apply the same fix to the second getter.
Secondly, in your inner loop in the JSX code, you will also iterate the _title
property. You probably don't want to include that in your output. So either change the Category
class to use a private field #title
instead of _title
(if your environment supports that syntax) or else, exclude properties that start with an underscore from your loop. For instance, by calling .filter
:
{Object.entries(category).filter(([s]) => s[0] !== "_")
.map(([s, c]) => {
return <li key={s}>{c.title}</li>
})}
Answered By - trincot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.