const dark = { backgroundColor: "#2c3343", color: "#c8e5c9" };
const light = { backgroundColor: "white", color: "black" };
return (
<>
<div className="my-5 container">
<h1>{props.heading}</h1>
<div className="mb-3">
<textarea
className="form-control"
id="myBox"
value={text}
rows={8}
onChange={handleOnChange}
style={{
backgroundColor: props.mode.backgroundColor,
color: props.mode.color,
}}
>
asd
</textarea>
</div>
</div>
</>
);
basically I am passing mode in props in this js file. Mode is a string which is either 'light' or 'dark'. On the basis of the props.mode value, I want to change color of my textbox. But css style is not happening on it. What to do? Am I doing something wrong while calling the objects. Like I want it to work in this way :-
(consider mode is == 'dark')
style = {{
backgroundColor: dark.backgroundColor,
color: dark.color,
}}
consider mode is 'light'
style = {{
backgroundColor: light.backgroundColor,
color: light.color,
}}
Also the objects light and dark that I have made gives warning that I haven't used them. I know I can use ternary operators instead of creating two separate objects and calling their values but I want to do it this way. So, I would appreciate if someone can point out the issue. Here is part of my code :-
const dark = {
backgroundColor: "#2c3343",
color: "#c8e5c9",
};
const light = {
backgroundColor: "white",
color: "black",
};
return (
<>
<div className="my-5 container">
<h1>{props.heading}</h1>
<div className="mb-3">
<textarea
className="form-control"
id="myBox"
value={text}
rows={8}
onChange={handleOnChange}
style={{
backgroundColor: props.mode.backgroundColor,
color: props.mode.color,
}}
You can dynamically access values on an object with the square brackets syntax.
const modes = {
light: {...},
dark: {...},
};
const thisMode = modes[props.mode];
// now use it like
color: thisMode.color
You need to use CSS dynamically so i have update your code it should work for you.
const customColor = {
dark: {
backgroundColor: "#2c3343",
color: "#c8e5c9",
},
light: {
backgroundColor: "white",
color: "black",
}
}
return (
<>
<div className="my-5 container">
<h1>{props.heading}</h1>
<div className="mb-3">
<textarea
className="form-control"
id="myBox"
value={text}
rows={8}
onChange={handleOnChange}
style={customColor[props.mode]}
/>
</div>
</div>
</>)
Either you can do the way @windowsill mentioned or do it the following way.
style={
props.mode === "light"
? {
backgroundColor: light.backgroundColor,
color: light.color,
}
: {
backgroundColor: dark.backgroundColor,
color: dark.color,
}
}