Search code examples
reactjstypescriptrenderingoffice-ui-fabrictsx

How do you set the value of a TextField from Dropdown Selection?


In the following code, I was curious as to how you would set the value of the following TextField. For this example, how do I set the TextField to the selected item in the Dropdown? If the user selects "TOP LEVEL" in the Dropdown, then I want to populate the TextField to be "TOP LEVEL". The Dropdown is called ChildComponent

import * as React from "react";
import ChildComponent from './Operations/ChildComponent';
import { DropdownMenuItemType, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown';
import { TextField} from 'office-ui-fabric-react/lib/TextField';
export interface ParentComponentState {
    selectedItem?: { key: string | number | undefined };
    value: {key: string};
  }

  export default class ParentComponent extends React.Component<{}, ParentComponentState> {
    constructor(props, context) {
        super(props, context);

      }
    public state: ParentComponentState = {
      selectedItem: undefined,
      value: undefined,
    };

  render(){
    const { selectedItem } = this.state;
    const options: IDropdownOption[] = [
        { key: 'blank', text: '' },
        { key: 'topLevelMake', text: 'Parents', itemType: DropdownMenuItemType.Header },
        { key: 'topLevel', text: 'TOP LEVEL' },
        { key: 'make', text: 'MAKE ITEM' },
        { key: 'divider_1', text: '-', itemType: DropdownMenuItemType.Divider },
        { key: 'Purchased', text: 'Purchases', itemType: DropdownMenuItemType.Header },
        { key: 'rawMaterial', text: 'RAW MATERIAL' },
        { key: 'buyItem', text: 'BUY ITEM' },
      ];
      return(
        <div>
            <ChildComponent 
                options={options} 
                selectedKey={selectedItem ? selectedItem.key : undefined}
                onChange={this._onChange}
            />
            <TextField
                name="textTest"
                label={"Test"}
            />
        </div>
          );
   }
   private _onChange = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
    this.setState({ selectedItem: item });
    let opValue = item.text;
    console.log(event);
    console.log(opValue);
  };
}

After inserting Muhammad's logic, here is the error I am getting. Do I need to add an onChange event for the TextField? and then put "this.state.selectedItem" in the handleChange event? Do I need to make a new child component and have the TextField rollup to ParentComponent?

enter image description here


Solution

  • You just need to assign that state in the value prop for the textField as you have the selectedItem in your state

     <TextFieid
        label={"Test"}
        styles={{ root: { width: 300 } }}
        value={this.state.selectedItem}
      />