Home > other >  Typescript React Textfield does not change value on Dropdown change
Typescript React Textfield does not change value on Dropdown change

Time:12-27

I have a Dropdown Field with options and a Textfield which should be used to store user input in an object array with key value pairs. This happens in the onchange event of textfield. Additionally the textfield should retrieve the data out of the array and show the value on change of the dropdown in the same textfield.

I am not sure if this is possible, I only tried to set the "defaultValue" attribute of the textfield dynamically.

The part with saving userinput in the object array works fine. But the value in the textfield doesnt change on onchange of dropdown. I get the selected value and therefore also the value out of the array while debugging.

I have also a problem with setting the initial value of dropdown element. I dont want it to be blank on init, instead it should have one of the values out of the optionset which I provide.

Dropdown: Where I set selectedValue

<Dropdown

    defaultValue={this.options["foo"]}  //<-- This doesnt work too
    id="Dropdown"
    options={this.options}
    onChange={(event: React.FormEvent<HTMLDivElement>, option?: IDropdownOption): void => {
       this.setState({
                        selectValue : option?.text
                     }, this.onNameChanged);
                     }
             }
 />

Textfield:

<TextField
 id="inputVarLang"
 defaultValue={this.state.arrayObj[this.state.selectValue as any]}
 placeholder={"---"}
 onChange={(event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement | HTMLDivElement>, 
 newValue?: string): void => {
                         this.setState({
                                   arrayObj: update(this.state.arrayObj 
                                   {[this.state.selectValue as any]: {$set: newValue ?? ""}})
                                        }, this.onNameChanged);
                             }
           }/>

It would be great if someone could help me with this.

CodePudding user response:

You need to use "value" prop of TextField instead of defaultValue, like this

<TextField
 id="inputVarLang"
 value={this.state.arrayObj[this.state.selectValue as any]}
 placeholder={"---"}
 onChange={(event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement | HTMLDivElement>, 
 newValue?: string): void => {
                         this.setState({
                                   arrayObj: update(this.state.arrayObj 
                                   {[this.state.selectValue as any]: {$set: newValue ?? ""}})
                                        }, this.onNameChanged);
                             }
           }/>
  • Related