I have the following code. I know their are multiple ways of doing this and I could make it using conditional return but I would like to know if theres a more efficient way of doing it.
This is my component example
export default function APIListThingy({
title = "List Component",
type = "dog",
}: {
title?: string;
type: "dog" | "cat" | "bunny";
}) {
I have "Dog" | "Cat" | "Bunny" to each have a specific set of visual changes (background color, text color), and functional from the API its calling to.
What would be the best way to do this?
Edit:
I have tried the following and works fine.
const variables = {
dog: {
bg: "#333",
icon: "dog-outline",
},
cat : {
bg: "#444",
icon: "cat-outline",
},
bunny : {
bg: "#555",
icon: "bunny-outline",
},
};
and I just call it with
variables[type]
CodePudding user response:
I'd say it would be simplier to create some generic component let's say Animal, that would accept those style values and apply them. Then make your APIListThingy to simply pass props to it like this:
<Animal {...variables[type]} />
So you were basically already doing the right thing.
Your variables
object/dictionary works as, so called, "lookup" mapping and imho is a better and more readable alternative to a switch-case