this is another geek here. I am learning reactjs now. I found this in my code while I was tring to create a Button
element for my app. My idea is to decide background color according to a prop
called type
. This is similar to a switch case. please go through the code to find problem.
const colors = {
primary: "#0d6efd",
secondary: "#adb5bd",
success: "#198754",
info: "#0dcaf0",
warning: "#ffc107",
danger: "#dc3545",
light: "#f8f9fa",
dark: "#212529",
};
let bg = ((cl) => {
colors[cl] || "#adb5bd";
})("primary");
let bg2 = ((cl) => colors[cl] || "#adb5bd")(type);
console.log(bg, bg2);
In console,
undefined '#adb5bd'
Did I miss something?
CodePudding user response:
You're not returning anything from your function. When you use curly brackets notation while writing a function you need to return explicitly.
let bg = ((cl) => {
return colors[cl] || "#adb5bd";
})("primary");
CodePudding user response:
I believe the easiest way to do is something like:
const Button = (props) => {
const { type = 'primary' } = props; // we get the type with destructuring
const colors = {
primary: "#0d6efd",
secondary: "#adb5bd",
success: "#198754",
info: "#0dcaf0",
warning: "#ffc107",
danger: "#dc3545",
light: "#f8f9fa",
dark: "#212529",
};
const color = colors[type];
return <button style={{backgroundColor: color}}>I am the button with random color</button>
}