Dynamic and Conditional Inline Style
We update styles dynamically — add or remove styles — using React state and button clicks.
Make Button for Dynamic Style
<button>Grey Theme</button>
<button>
Default Theme
</button>
Use State for Style Object
const [cardStyle, setCardStyle] = useState({
border: "1px solid #ccc",
width: "200px",
boxShadow: "1px 2px 3px 0px #cccccc57",
margin: "10px",
});
const [textColor, setTextColor] = useState("black");
Update style on button click
<button onClick={() => updateTheme("#ccc ", "red")}>Grey Theme</button>
<button onClick={() => updateTheme("white", "black")}>
Default Theme
</button>
const updateTheme = (bgColor, textColor) => {
setCardStyle({ ...cardStyle, backgroundColor: bgColor });
setTextColor(textColor);
};
Multiple cards create
Create multiple cards like this and apply the updated styles:
Show them in grid form when Click on button
Create Button
<button>Toggle Grid</button>
Define a state
const [grid, setGrid] = useState(true);
condition
<div style={{ display: grid ? "flex" : "block", flexWrap: "wrap" }}>
onClick event
<button onClick={() => setGrid(!grid)}>Toggle Grid</button> // when grid is true make it false /