Dave
Dave

Reputation: 8109

How to put a hyperlink in the label of a dash Checkbox

How can I have the label of a dcc.Checkbox be a hyperlink?

Imagine taking the first example here and having "New York City", "Montreal", etc. each be a hyperlink.

Neither setting the label to be '''<a href="...">text</a>''' nor setting it to be a html.A object works.

Upvotes: 0

Views: 480

Answers (1)

bas
bas

Reputation: 15462

You could do it with some javascript:

const labelUrls = [
  "https://www.google.com/search?q=New+York+City",
  "https://www.google.com/search?q=Montr%C3%A9al",
  "https://www.google.com/search?q=San+Francisco",
];

window.addEventListener("load", function () {
  const labels = document.querySelectorAll("label");
  labels.forEach((label, index) => {
    const previousLabel = label.innerHTML;
    const previousLabelText = label.innerText;

    label.innerHTML = previousLabel.replace(
      previousLabelText,
      `<a href=${labelUrls[index]}>${label.innerText}</a>`
    );
  });
});

So the idea above is to create a list of urls that you want to navigate to, where each url corresponds to an option label in the checklist. Make sure the order of the urls corresponds to the order of the options in your Checklist component.

When the page has loaded we look for all labels. We use innerHTML to get the full label html as a string. We use innerText to get the text inside the label (input excluded). Then we set the new label to the old label innerHTML, but where the old label's textContent is replaced with an anchor tag.

I've passed label to querySelectorAll in this example, but in a page with more elements its probably a better idea to give the Checklist an id or className and target the labels using the Checklist's identifier.

For how to include Javascript in dash apps, see this.

But the basic flow is to create an assets folder in the root directory and to put a javascript file inside with the code.

Upvotes: 1

Related Questions