0

I'm using Semantic UI React to create a select country dropdown. In order to get values that are passed as attributes to a <div role=option />. In order to get the selected div I use this:

  handleSelectCountry = (e, props) => {
    const selected = $('div.item[aria-selected=true]');
    const flag = selected.get(0).children[0].className;
    console.log(selected);
    this.setState({ country: props.value, flag });
  };

When logged, it logs the previous selected div as <div role="option" aria-selected="false">Previous selected</div>

However, using the same selector in the Chrome console gives the correct <div role=option aria-selected="true">Current selected</div>.

The DropDown code is (from semantic-ui-react):

<Dropdown
  fluid
  required
  placeholder="Select Country"
  search
  selection
  options={Form.countryList}
  value={country}
  onChange={this.handleSelectCountry}
/>
Kyle
  • 1
  • 1
    You probably shouldn't be using jQuery. Perhaps look into using a ref instead...? – Andy Dec 10 '18 at 23:08
  • @Andy, This was my initial thought however, the options are generated by semantic ui and so I'm not sure how I would go about assigning and/or using refs. – Kyle Dec 10 '18 at 23:21
  • There is a [ref addon](https://react.semantic-ui.com/addons/ref/#types-ref). Would that help? – Andy Dec 10 '18 at 23:32
  • I used this answer to solve my problem: https://stackoverflow.com/a/51227478/10773032 – Kyle Dec 11 '18 at 00:28

1 Answers1

0

The onChange handler is called with its first argument to be an instance of a React SyntheticEvent [1]

The currentTarget can be retrieved from it and the icon tag contained in it queried for.

const onChange = (event, data) => {
  const [ icon ] = event.currentTarget.getElementsByTagName('i');
  const flag = icon.className;

  this.setState({ country: props.value, flag });
}
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
  • Thanks for your answer. This works for a click event, but not for an arrow through the drop down and enter event. Edit: I believe this is due to currentTarget becoming document on an arrow and enter event. – Kyle Dec 10 '18 at 23:29