javascripthtmlreactjsoffice-ui-fabric

not able to get choice group target id to set values dynamically


This is my Choice Group element

 <ChoiceGroup defaultSelectedKey="No"
  options={[{ key: 'Yes', text: 'Yes' },{ key: 'No', text: 'No' }]}
  onChange={this._onChange}
  id={'ChoiceGroup1'}
  name={this.state.currentUser} />

and my onChange function

public _onChange=(ev, option: IChoiceGroupOption)=> {
console.log(ev,option); } 

but i am not able get target.id value. The target shows null but in case of Textfield i am able to get name and target of component


Solution

  • You can manually pass the selected item's id to the _onChange function.

    Based on the props and the used case, i assume your ChoiceGroup component maps through the "options" prop and renders another component. If that's the case, you can tweak it a little bit to make it pass the clicked item up to the parent component (so you can decide what to do with it).

    So in your ChoiceGroup component add

    {options.map(option =>
    <ChoiceGroupOption
      onClick={e => onItemSelected(option)}
    />}
    
     <ChoiceGroup defaultSelectedKey="No"
       options={[{ key: 'Yes', text: 'Yes' },{ key: 'No', text: 'No' }]}
       onItemSelected={item => this._onChange(e, item.id)}
       id={'ChoiceGroup1'}
       name={this.state.currentUser} />
    

    Then in the event handler put this:

    public _onChange = (ev, selectedId)=> {
        console.log('ID: ', selectedId);
    }