The following code is to create a DropdownMenuItem with a for loop.
import dash_bootstrap_components as dbc
from dash import Dash, html
tickers = ['MSFT', 'ADB', 'ABBV', 'A', 'TXN', 'MCHP']
app = Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
dropdown_menu = dbc.DropdownMenu(
id='companies_id',
label='Tickers',
children=[dbc.DropdownMenuItem(ticker) for ticker in tickers]
)
layout_div = html.Div([dropdown_menu])
app.layout = dbc.Container(layout_div)
if __name__ == '__main__':
app.run(debug=True)
How can I add and id parameter for each DropdownMenuItem with the loop that created the DropdownMenuItems?
Hi @mahmoud899
You can simply modify your code as below, this will give each menue item the same id as the element name
import dash_bootstrap_components as dbc
from dash import Dash, html
# List of ticker symbols
tickers = ['MSFT', 'ADB', 'ABBV', 'A', 'TXN', 'MCHP']
# Initialize Dash app
app = Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
# Create dropdown menu with DropdownMenuItems containing ids
dropdown_menu = dbc.DropdownMenu(
id='companies_id',
label='Tickers',
children=[dbc.DropdownMenuItem(ticker, id=ticker) for ticker in tickers]
)
# Define layout with dropdown menu
layout_div = html.Div([dropdown_menu])
# Set layout for the Dash app
app.layout = dbc.Container(layout_div)
# Run the app
if __name__ == '__main__':
app.run(debug=True)
3 Likes
To add to this: as you’re starting with dash, you might look into pattern matching callbacks. At first look they seem to be complicated, but once you get a understanding for it, they become really handy.