gamcoh / st-card

Streamlit component for UI cards
https://pypi.org/project/streamlit-card/
MIT License
116 stars 19 forks source link

Multiple card on click behaviour #31

Closed tombeteende closed 5 months ago

tombeteende commented 5 months ago

I have multiple cards, roughly creating by -

for my_card in enumerate(my_cards):
     card(**my_card)

Now I want to add a functionality that when I click them it writes down something, let's say the title, e.g st.write(my_card['title'])

When adding something like -

for my_card in enumerate(my_cards):
     card(**my_card, on_click=lambda: st.write(my_card))

It writes it for all the cards that were previously clicked. Is there a way to disable previous clicks / identify the last clicked card? or any other option that will allow me to control the behavior?

gamcoh commented 5 months ago

This has to do with the way streamlit handles state,

You could try something like this:

current_card_clicked = -1

for my_card in enumerate(my_cards):
     card(**my_card, on_click=lambda: current_card_clicked = my_card["id"])

st.write(my_cards[current_card_clicked]["title"])
tombeteende commented 5 months ago

Does it work for you when you click the one card then the other, and then the first one back? For me it always returns the one which was clicked the last for the first time

gamcoh commented 5 months ago

Again, this isn't an issue related to the package, you have to find pythonic ways to make it work.

tombeteende commented 5 months ago

I understand it does not relate to the package. It also relates not to Python but rather to how streamlit deals with click events. Having said that, the suggested solution does not work.