How to create streamlit app with pagination

I am trying to create a streamlit app that uses pagination to display data. I have written the example code below. My issue is that clicking either button does not change the page. It only changes once I manually refresh the app ( by pressing ‘R’). Am I doing something wrong here or is this a bug?

import streamlit as st

if "page" not in st.session_state:
    st.session_state.page = 1


st.title("Test")

if st.session_state.page == 1:
    st.write("Page 1")
elif st.session_state.page == 2:
    st.write("Page 2")
else:
    st.write("No page")

if st.button("Next"):
    st.session_state.page = 2

if st.button("Previous"):
    st.session_state.page = 1

Its because you check for the session state before the button, this should work

import streamlit as st

if "page" not in st.session_state:
    st.session_state["page"] = 1


st.title("Test")

empty = st.empty()

if st.button("Next"):
    st.session_state["page"] = 2

if st.button("Previous"):
    st.session_state["page"] = 1

if st.session_state["page"] == 1:
    empty.write("Page 1")
elif st.session_state["page"] == 2:
    empty.write("Page 2")
else:
    empty.write("No page")

streamlit-dummy-2021-11-17-10-11-38

Hope it helps!

You can use the Router module from Mohamed-512/Extra-Streamlit-Components: An all in one place, to find complex or just not available components by default on streamlit. (github.com). It takes care of all that under the hood, and provides custom routes for your app.