1

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?

1
  • Create a useMemo to render the card with dependency as the cardColor state. Whenever you update the cardColor state, it will rerender. Commented Mar 10, 2021 at 6:57

1 Answer 1

1

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 }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.