Search code examples
reactjstypescriptsemantic-ui-react

Dropdown onchange doesnt work : React+ Typescript+ semantic-ui-react


I am trying to bring up a dropdown using semantic-ui-react with typescript. The problem here I am facing is , I am unable to attach change handlers to it. It is throwing the following error " Type 'SyntheticEvent' is not assignable to type 'ChangeEvent' ".

//Importing Dropdown
import Dropdown from 'semantic-ui-react/dist/commonjs/modules/Dropdown';

//options array
const options = [
  { key: 1, text: 'Location 1', value: 1 },
  { key: 2, text: 'Location 2', value: 2 },
  { key: 3, text: 'Location 3', value: 3 },
]

//state object
this.state ={
  value : ''
}

//Dropwdown change event
dropdownChange = (event: React.ChangeEvent<HTMLSelectElement> ,{value}) =>{
   this.setState({ value });
}

//Rendering Drop down
render()
{
  return(
      <Dropdown  
        options={opitons}
        name="value"  
        value={this.state.value}
        onChange={this.dropdownChange}
      />
  )
}

Solution

  • This is happening because the library is not using a ChangeEvent is using a SyntheticEvent

    The typings for the onChange function on the Dropdown element are:

    onChange?: (event: React.SyntheticEvent<HTMLElement>, data: DropdownProps) => void
    

    You can see them here https://github.com/Semantic-Org/Semantic-UI-React/blob/master/src/modules/Dropdown/Dropdown.d.ts#L143

    so you should change this line:

    dropdownChange = (event: React.ChangeEvent<HTMLSelectElement> ,{value}) =>{
    

    to:

    dropdownChange = (event: React.SyntheticEvent<HTMLElement> ,{value}) =>{