I know this seems like an easy question, but I cannot find the answer.
I am switching from Streamlit to Dash, and that’s part of the problem. I am very new to Dash, only in the past few days.
Still, the answer to this one should be obvious.
In this text area, the user pastes a cooking recipe. I need to iterate over the lines in that recipe with a for loop. When I use the “value” to identify the submitted recipe, it does not work. When I use the “id”, it does not work. I have tried a dozen different, seemingly apparent ways to identify the text in the input textarea. I cannot make it work.
So how should I identify the contents of a text area to process it with a for loop?
Here is the code for the textarea:
app.layout = html.Div([
dcc.Textarea(
id='textarea-state-example',
value='recipe',
style={'width': '1000%', 'height': 200},
placeholder='Please paste your recipe here.',
className='recipe-textarea',
contentEditable='true'
),
html.Button('Submit', id='textarea-state-example-button', n_clicks=0),
html.Div(id='textarea-state-example-output', style={'whiteSpace': 'pre-line'})
])
Here is the for loop:
with open ("recipe_contents.txt", "w", encoding='utf-8') as recipe_contents:
for line in recipe:
recipe_contents.write(line)
print("Recipe contents witten to file.")
Thank you.
Hi,
You should use “value”, but in a callback. Something like:
@app.callback(
Output('textarea-state-example-output', 'children'),
Input('textarea-state-example-button', 'n_clicks'),
State('textarea-state-example', 'value')
)
def update_recipe(n_clicks, textarea_value):
if n_clicks > 0:
with open ("recipe_contents.txt", "w", encoding='utf-8') as recipe_contents:
recipe = textarea_value.split("\n")
for line in recipe:
recipe_contents.write(line)
return "Recipe contents witten to file."
P.S: Not sure if you want width = 1000% or if it was a typo…
1 Like
Yep. that worked. Thank you.
Since that same callback already existed in my code preceding the function, I don’t understand how it made a difference.
Granted, I have much to learn about callbacks, so I yield to a higher power on that one.
I also had to move the return statement out of the loop or it broke after the first line. The 1000% was a typo though I was trying to figure out how to reduce the textarea to 80% without throwing the Submit button out of alignment.
But I will save that lesson for another day.
Thanks again.
Robert
In case this is helpful to someone in the future:
def update_recipe(n_clicks, value):
if n_clicks > 0:
with open("temp/recipe_contents.txt", "w", encoding='utf-8') as recipe_contents:
recipe = value.split('\n')
for line in recipe:
print(line)
recipe_contents.write(line)
recipe_contents.write('\n')
return "Recipe contents written to file."
1 Like