Streamlit Pages on Button Press (not on sidebar)

Viewed 35

With streamlit, I want to have the user click a button on one page and get taken directly to another page. I also don't want the sidebar to pop up, so I don't want to use that to switch between pages. Just a direct connection from one page to the next through a button on that page. Is there a way to do this?

1 Answers

At the moment it seems not possible without using a sidebar. According to this issue, they noticed the issues and have it on their list. Also in the issue, there is a somehow tacky workaround to work with buttons to go to the next and previous page using this code:

# Import packages
import streamlit as st
from streamlit.components.v1 import html

# create navigation
def nav_page(page_name, timeout_secs=3):
    nav_script = """
        <script type="text/javascript">
            function attempt_nav_page(page_name, start_time, timeout_secs) {
                var links = window.parent.document.getElementsByTagName("a");
                for (var i = 0; i < links.length; i++) {
                    if (links[i].href.toLowerCase().endsWith("/" + page_name.toLowerCase())) {
                        links[i].click();
                        return;
                    }
                }
                var elasped = new Date() - start_time;
                if (elasped < timeout_secs * 1000) {
                    setTimeout(attempt_nav_page, 100, page_name, start_time, timeout_secs);
                } else {
                    alert("Unable to navigate to page '" + page_name + "' after " + timeout_secs + " second(s).");
                }
            }
            window.addEventListener("load", function() {
                attempt_nav_page("%s", new Date(), %d);
            });
        </script>
    """ % (page_name, timeout_secs)
    html(nav_script)

# Example
if st.button("< Prev"):
    nav_page("Foo")
    st.markdown('# Page 1')
if st.button("Next >"):
    nav_page("Bar")
    st.markdown('# Page 2')
Related