Skip to content

Instantly share code, notes, and snippets.

@andfanilo
Last active June 26, 2021 00:00
Show Gist options
  • Save andfanilo/18ef56880b8c90bb2bd73ebd709521d1 to your computer and use it in GitHub Desktop.
Save andfanilo/18ef56880b8c90bb2bd73ebd709521d1 to your computer and use it in GitHub Desktop.
import streamlit.components.v1 as components
mycomponent = components.declare_component(
"mycomponent",
path="./" # instead put index.html and __init__.py into mycomponent folder and put ./mycomponent. Gist does not like subdirectories
)
<html>
<body>
<!-- Set up your HTML here -->
<input id="myinput" value="" />
<script>
// ----------------------------------------------------
// Just copy/paste these functions as-is:
function sendMessageToStreamlitClient(type, data) {
var outData = Object.assign({
isStreamlitMessage: true,
type: type,
}, data);
window.parent.postMessage(outData, "*");
}
function init() {
sendMessageToStreamlitClient("streamlit:componentReady", {apiVersion: 1});
}
function setFrameHeight(height) {
sendMessageToStreamlitClient("streamlit:setFrameHeight", {height: height});
}
// The `data` argument can be any JSON-serializable value.
function sendDataToPython(data) {
sendMessageToStreamlitClient("streamlit:setComponentValue", data);
}
// ----------------------------------------------------
// Now modify this part of the code to fit your needs:
var myInput = document.getElementById("myinput");
// data is any JSON-serializable value you sent from Python,
// and it's already deserialized for you.
function onDataFromPython(event) {
if (event.data.type !== "streamlit:render") return;
myInput.value = event.data.args.my_input_value; // Access values sent from Python here!
}
myInput.addEventListener("change", function() {
sendDataToPython({
value: myInput.value,
dataType: "json",
});
})
// Hook things up!
window.addEventListener("message", onDataFromPython);
init();
// Hack to autoset the iframe height.
window.addEventListener("load", function() {
window.setTimeout(function() {
setFrameHeight(document.documentElement.clientHeight)
}, 0);
});
// Optionally, if the automatic height computation fails you, give this component a height manually
// by commenting out below:
//setFrameHeight(200);
</script>
</body>
</html>
import streamlit as st
import mycomponent
value = mycomponent(my_input_value="hello there")
st.write("Received", value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment