Kinode
Kinode

Reputation: 23

How to make the callback function run after the button is created and clicked?

I'm very new to Dash and I'm trying to create a map with clickable dots on it, dots are the positions of places. A User can add the clicked position to his/her saved places by click the dot and click a button created by clicking it in a Div next to the map. My problme is that after the button is created(User clicked the dot), the callback function for button will run automatically(print the coordinate), but what I need is running the function(print the coordinate) when user clicks the button.

Here is the code:

@app.callback(
    dash.dependencies.Output('button_list', 'children'),
    [dash.dependencies.Input('map', 'clickData')])
def display_click_data(clickData):
    if clickData is None:
        return 'Click on any points to see more info'
    else:
        coordinate_lon = clickData['points'][0]['lon']
        coordinate_lat = clickData['points'][0]['lat']
        coor = str(coordinate_lon)+","+str(coordinate_lat)
        return html.Button('add to saved locations', id='add_to_saved', value=coor),\
               html.Div(id='button_return', children=[])

As you can see, the function will return a button in the id='button_list' part, and a coordinate saved in the value of the Button named 'add to saved locations'. And I created a callback function for the button:

@app.callback(
    dash.dependencies.Output('button_return', 'children'),
    [dash.dependencies.Input('add_to_saved','value')],
)
def add_to_saved(value):
    print(value)
    return

I want to print the value(the coordinates) when the button is clicked, but right now this function will automatically run after the button created(user click the dot) Please help! Thank you for the help in advance!

Upvotes: 2

Views: 2797

Answers (1)

coralvanda
coralvanda

Reputation: 6616

When you add a component to the layout in this way, the related callback will run. However, the button should have n_clicks=0 at the time, so you can use that to your advantage. Try this callback:

@app.callback(
    dash.dependencies.Output('button_return', 'children'),
    [dash.dependencies.Input('add_to_saved','n_clicks')],
)
def add_to_saved(value):
    if value:
        print(value)
        return value
    return ''

Edit: changed Input prop to n_clicks

Upvotes: 1

Related Questions