"Show more items" functionality

I’d like to add a feature to my streamlit app where a list ends with a “Show more” button, and pressing the button queries for more data, and puts the “Show more” button at the end of the extended list. Exactly like how google scholar implements it: https://scholar.google.com/citations?user=JicYPdAAAAAJ&hl=en&oi=ao

Using the https://gist.github.com/tvst/036da038ab3e999a64497f42de966a92 SessionState.py class, I came up with something nice that’s quite similar:

import random
import time
import streamlit as st
import SessionState


@st.cache
def long_calculation(i):
    time.sleep(1)
    return 1000 * i + random.randrange(100)


def main():
    session_state = SessionState.get(length=5)
    if st.button("Show more"):
        session_state.length += 5
    for i in range(1, session_state.length + 1):
        st.write("item %d: %d" % (i, long_calculation(i)))


main()

The only difference between this and my imagined ideal solution is that here the “Show more” button is at the beginning, not at the end where it should be. Unfortunately this is extremely bad UX for long lists, and I’m stuck here. Is there a way to fix this issue, either along these lines, or starting from scratch?

Hey @danielvarga -

If I’m correctly understanding what you’re after, you can accomplish this with some minor abuse of RerunException (which is currently undocumented and subject to change):


from streamlit.ScriptRequestQueue import RerunData
from streamlit.ScriptRunner import RerunException

def main():
    session_state = SessionState.get(length=5)
    for i in range(1, session_state.length + 1):
        st.write("item %d: %d" % (i, long_calculation(i)))
    if st.button("Show more"):
        session_state.length += 5
        # Force an immediate rerun of the report. This is a bit
        # ugly, but it ensures that the report will be rerun
        # *after* session state gets updated.
        raise RerunException(RerunData(widget_state=None))

Hopefully, when SessionState becomes a proper Streamlit citizen, simply modifying it will be enough to trigger a rerun, and these gymnastics won’t be necessary!

1 Like

I like this expand content idea, what would be nice if a component like st.markdown which has content which is easily truncated had an option like st.markdown(txt, show_lines=5), so it only displays the first few lines and puts in a expand icon to show all the text.

Useful for things like putting in a block of explainer text for different objects. And other uses, like showing the head/tail of a log with an expand option to show all the log.

1 Like

That’s awesome, @tim, thank you! What’s streamlit’s current roadmap for solidifying this part of the API?

It’s currently being tracked in this Github issue . I don’t know there’s a fixed timeline decided for this feature yet, but it’s being discussed and I think we’ll be working on it in earnest soon!

1 Like