How to highlight active page with a className - Plotly Dash

Viewed 28

I have a classic multi page app made in Plotly Dash, but I can't figure out how to highlight a page in the navigation that is currently visited. I managed to get the active pathname with a callback, but I still don't know how I can use this to add a className "active" to one of the links in the navigation.

@app.callback(Output("print", "children"), [Input("url", "pathname")])
def callback_func(pathname):
    print(pathname)
    return pathname

This is how I render my navigation:

html.Div(
  className="items",
  children=[
    html.Div(
      dcc.Link(
         f"{page['name']}",
         href=page["relative_path"],
      )
    )
    for page in dash.page_registry.values()
  ],
),
1 Answers

Below is a working example that does what you're looking for!

from dash import Dash, dcc, html, Input, Output, ALL
import dash


app = Dash(__name__)
app.layout = html.Div([
    dcc.Location(id="url"),
    html.Div([ 
        dcc.Link(f"LINK {val}", href="/" if val == 0 else f"/link{val}", 
            id={"type":"link-navbar", 
                "index": "/" if val == 0 else f"/link{val}"}, 
            style={"marginRight":"16px"}) 
        for val in range(3)]),
])


@app.callback(Output({"type":"link-navbar", "index":ALL}, "className"), 
[Input("url", "pathname"),Input({"type":"link-navbar", "index":ALL}, "id")])
def callback_func(pathname, link_elements):
    return ["active" if val["index"] == pathname else "not-active" for val in link_elements]

if __name__ == '__main__':
    app.run_server(debug=True)

and in your style.css file:

.active {
    background: red;
    color:aqua
}

.not-active{
    background: rgb(132, 0, 255);
    color:rgb(255, 81, 0)
}

Hope it can solve your problem;

Regards,
Leonardo

Related