Add hyperlink for st.metrics.value

Summary

Hi, I’m using st.metrics as a data display component, and I want to contain a hyperlink in the value, but found the value won’t be rendered as markdown or html. Any way to do this?

Many thanks!

Steps to reproduce

Code snippet:

row[j].metric(
    label=field.metadata.get("label", field.name),
    value=getattr(info, field.name),
    help=field.metadata.get("help"),
)

For example, when the value is [Paper name](https://nature.com), I can only get the raw text as body.

image

There are two parts: first is actually making it into a link and the second if you are trying to stay within your app, within the same session.

To deal with the first part by itself, let’s say you want to open another tab to another site when you click on a metric. Here’s a proof of concept, though it makes every metric on a page go to the same place (streamlit.io in my example):

import streamlit as st

st.metric(label='My Metric', value=10000, delta=10)

js = '''
<script>
    var metrics = window.parent.document.querySelectorAll('[data-testid="metric-container"]');
    metrics.forEach((metric) => {
        metric.onclick = function() {
            window.open('https://www.streamlit.io/');
        }
    })
</script>'''

st.components.v1.html(js)

To expand it to your case, you would need set the url conditionally, say based on the label you used in the metric. Here’s a related example that implements a function to change button colors based on their labels:



Now…if you are trying to navigate within your app, you’ll have to layer in even more complication because at this point the only way I know of doing from the front end is to grab the page links by javascript and emulate a click on them… Top-level links from a component iframe? - #8 by mathcatsand

PS: You’d also need to add in an edit to have some hover effect to show it’s a link which can be done as an add-on to the javascript making it a link, or separately though CSS.

Hi,
The above snippet gets all the metric-container on the document.
If there are two metric-container and when clicked both opens same page.
But I want to open different sites when clicked.
How can i achieve that I tried using xpath like below, however it doesn’t seem to work.

var metrics = window.parent.document.querySelector(‘div[text=“link”]’);

Thank you.

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