Reputation: 11
This feels like a simple question, but I can't seem to find any hook based tutorials on it (most are using classes).
Let's say I have a simple card component with a variable background color. The user picks a color (cardColor), and then clicks a button (renderButton). This button will render that card component with a background of cardColor (e.g. the user picks "red" and the card is rendered with a "red" background). Then, if the user were to pick another color and click renderButton, the old card would be replaced with a new card with a background of cardColor. How would one go about doing this with hooks? The difference I see with my scenario and ones online is that mine does not simply hide and reveal a component, but rather creates the component based on user input.
In my actual implementation, the card's image, text, and other attributes are being pulled from a database using queries that the user dictates. All this works fine and the cards render accordingly. I just can't seem to figure out how to get the cards to appear/update with the click of a button.
Can anyone point me in the right direction?
Upvotes: 1
Views: 272
Reputation: 117
First create a state for card color, then for the button add a onClick event to set new card color. In the card use inline css to set the color. Whenever there is a change in cardColor state, the card will rerender.
const [cardColor, setCardColor] = useState('white')
onClick={() => {
setCardColor('red')
}}
style={{ color: cardColor }}
Upvotes: 1