Button with Link that changes depending on Input

I’m trying to create a Search bar where you Input a Text which then adds to the href link of the button.

Using the example below

import dash_bootstrap_components as dbc
from dash import Input, Output, html


search_bar = dbc.Row(
    [
        dbc.Col(dbc.Input(id="input",type="search", placeholder="Search")),
        dbc.Col(
            dbc.Button(
                "Search", color="primary", className="ms-2", n_clicks=0
                href=f"https://www.google.com/{**OUTPUT**}"
            ),
            width="auto",
        ),


@app.callback(Output("output", "children"), [Input("input", "value")])
def output_text(value):
    return value

I basically want to use the returned value in the f-String of the href link within the Button.

In the example above id=“output” would contain the input value.

but in my example i can’t use it. If i would use for example href=f"https://www.google.com/{id=“output”}" it won’t work because the f-string thinks i want to say id=https:/…

Is there any other way to achieve this? Or ideally can you define the output as a direct value which i can use in the Link?

Why don’t you update the href of your button via callback?

callback(
    Output("your-button-id", "href"),
    Input()
)
...

You just have to add the id to your dbc.Button()

1 Like

Thanks! I’m still trying to wrap my head around Callbacks.

But how would i get it to insert the value into the f-string?

Wouldn’t i have to insert the full html address like this?

Yes, you understood perfectly.

Here an example, maybe it helps you.

from dash import Dash, Input, Output
import dash_bootstrap_components as dbc

app = Dash(
    __name__,
    external_stylesheets=[dbc.themes.BOOTSTRAP]
)


app.layout = dbc.Row(
    [
        dbc.Col(
            dbc.Input(
                id="input",
                type="search",
                placeholder="Search"
            )
        ),
        dbc.Col(
            dbc.Button(
                id='btn',
                children="Search",
                color="primary",
                className="ms-2",
                n_clicks=0,
                href="https://www.google.com/",
                target="/"
            ),
            width="auto",
        )
    ]
)


@app.callback(
    Output("btn", "href"),
    Input("input", "value"),
    prevent_initial_call=True
)
def output_text(value):
    return f"https://www.google.com/search?q={value}"


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

Feel free to ask for clarification / explanation :raised_hands:

2 Likes