Sidebar html box disappears

Summary

sidebar html box disappears with some words searched in the search box (I didn’t find a pattern in the words)

I have a problem that I can’t understand in my sidebar. In my code, there are clickable cards that must insert information into a box created with HTML in the sidebox. This happens perfectly, but with certain words (I didn’t find a pattern) the my folder box disappears as soon as you search in the search box. Just so you understand, the mechanism for transferring information from the card to the sidebar (via session state) continues to work because if we go to the next page, the my folder box will be updated there and if we return to the home page, my folder will work again. As I said, this only happens with some words, while with others everything works normally

Steps to reproduce

Code snippet :

# Import libraries
import streamlit as st
import pandas as pd
import re

# Page setup
st.set_page_config(page_title="UN", page_icon="🌍", layout="wide")
st.title("Search for a resolution")

# read file
df = pd.read_csv('nl.csv')
df['date_p'] = pd.to_datetime(df['date_p']).dt.date

# Use a text_input to get the keywords to filter the dataframe
text_search = st.text_input("by title", value="")
text_search2 = st.text_input("by UN Document Symbol", value="")

# Filter the dataframe using masks
m1 = df["topic"].str.contains(text_search)
m2 = df["content"].str.contains(text_search)
df_search = df[m1 | m2]

st.write(f"Number of results: {df_search.shape[0]}")

# Limpar a entrada text_search2 para escapar de caracteres especiais
text_search2_sanitized = re.escape(text_search2)

# Filter the dataframe using masks
m3 = df["res_id2"].str.contains(text_search2_sanitized, na=False, regex=True)
df_search2 = df[m3]

# Show the results, if you have a text_search
#if text_search:
#    st.write(df_search)
#elif text_search2:
#    st.write(df_search2)

# Another way to show the filtered results
# Show the cards
# Show the cards

N_cards_per_row = 3

selected_card_info = {}

# Defina 'selected_card' no início do script
selected_card = st.session_state.get('selected_card', None)

# Verificar se algum dos buscadores foi preenchido
if text_search or text_search2:
    # Resultados do primeiro buscador
    if text_search:
        for n_row, row in df_search.reset_index().iterrows():
            i = n_row % N_cards_per_row
            if i == 0:
                st.write("---")
                cols = st.columns(N_cards_per_row, gap="large")
            
            # Criar o card clicável
            with cols[n_row % N_cards_per_row]:
                button_label = f"{row['location']} - {row['resn']} - {row['date_p']}\n" \
                            f"**{row['topic']}**\n" \
                            f"{row['in_deg']} citations"
                
                if st.button(button_label):
                    selected_card = {
                        "location": row['location'],
                        "date": row['date_p'],
                        "topic": row['topic'],
                        "res_id2": row['res_id2'],
                        "content": row['content'],
                        "cluster_wt": row['cluster_wt']
                    }
                    st.session_state.selected_card = selected_card

    # Resultados do segundo buscador
    if text_search2:
        for n_row, row in df_search2.reset_index().iterrows():
            i = n_row % N_cards_per_row
            if i == 0:
                st.write("---")
                cols = st.columns(N_cards_per_row, gap="large")
            
            # Criar o card clicável
            with cols[n_row % N_cards_per_row]:
                button_label = f"{row['location']} - {row['resn']} - {row['date_p']}\n" \
                            f"**{row['topic']}**\n" \
                            f"{row['in_deg']} citations"
                
                if st.button(button_label):
                    selected_card = {
                        "location": row['location'],
                        "date": row['date_p'],
                        "topic": row['topic'],
                        "res_id2": row['res_id2'],
                        "content": row['content'],
                        "cluster_wt": row['cluster_wt']
                    }
                    st.session_state.selected_card = selected_card

# Sidebar logic here

if "selected_card" in st.session_state:
    
    st.sidebar.subheader("My folder")
    st.sidebar.markdown(
        f"""
        <div style="border: 1px solid #ccc; padding: 10px; border-radius: 5px;">
            <p style="margin: 0;"><strong>Selected resolution:</strong></p>
            <p style="margin: 0;">Origin Committee: {selected_card['location']}</p>
            <p style="margin: 0;">Date: {selected_card['date']}</p>
            <p style="margin: 0;">Title: {selected_card['topic']}</p>
            <p style="margin: 0;">Symbol: {selected_card['res_id2']}</p>
        </div>
        """,
        unsafe_allow_html=True
    )

else:
    st.sidebar.subheader("My folder")
    st.sidebar.markdown(
        """
        <div style="border: 1px solid #ccc; padding: 10px; border-radius: 5px;">
            <p style="margin: 0;">Select a resolution to display information.</p>
        </div>
        """,
        unsafe_allow_html=True
    )

imagem = "resona_logo.png"
st.sidebar.markdown("<br>", unsafe_allow_html=True)
st.sidebar.image(imagem, use_column_width=False, width=305)```

Hey @arthurrslira ,

I’m not sure I understand what you desire to change. Can you please provide a deployed version of your code?

I tried to recreate your issue with the code provided but I do not have access to the csv you are using nor, the format for it. I am unsure how the data is structured.

Can you provide a preview of the csv or provide a deployed link to your project please?

  • Jyo

hello, @DevTechJr, many thanks for responding me but I already came to a solution. i had to put the logic of sidebar in the begining of the code

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.