Search code examples
reactjsreact-hookssemantic-ui

How to implement AddAdiditions in React Sematic UI using Hooks?


I want to have a drop down in my application which allows the user to add an item to the dropdown. I am using React Sematic UI. Sematic UI Dropdown ALlowAdditions

I am new to react hooks and I want to know how I can implement the onChange and onAddition function using hooks.

import React, { Component } from 'react'
import { Dropdown } from 'semantic-ui-react'

const options = [
  { key: 'English', text: 'English', value: 'English' },
  { key: 'French', text: 'French', value: 'French' },
  { key: 'Spanish', text: 'Spanish', value: 'Spanish' },
  { key: 'German', text: 'German', value: 'German' },
  { key: 'Chinese', text: 'Chinese', value: 'Chinese' },
]

class DropdownExampleAllowAdditions extends Component {
  state = { options }

  handleAddition = (e, { value }) => {
    this.setState((prevState) => ({
      options: [{ text: value, value }, ...prevState.options],
    }))
  }

  handleChange = (e, { value }) => this.setState({ currentValue: value })

  render() {
    const { currentValue } = this.state

    return (
      <Dropdown
        options={this.state.options}
        placeholder='Choose Language'
        search
        selection
        fluid
        allowAdditions
        value={currentValue}
        onAddItem={this.handleAddition}
        onChange={this.handleChange}
      />
    )
  }
}

export default DropdownExampleAllowAdditions

Any help would be greatly appreciated. Thanks in advance :)


Solution

  • import React, { useState } from "react";
    import { Dropdown } from "semantic-ui-react";
    
    const options = [
      { key: "English", text: "English", value: "English" },
      { key: "French", text: "French", value: "French" },
      { key: "Spanish", text: "Spanish", value: "Spanish" },
      { key: "German", text: "German", value: "German" },
      { key: "Chinese", text: "Chinese", value: "Chinese" }
    ];
    
    const DropDownWithHooks = () => {
    
      const [dropDownOptions, setDropDownOptions] = useState(options);
      const [currentValue, setCurrentValue] = useState("");
    
      const handleAddition = (e, { value }) => {
        setDropDownOptions((prevOptions) => [
          { text: value, value },
          ...prevOptions
        ]);
      };
    
      const handleChange = (e, { value }) => setCurrentValue(value);
    
      return (
        <Dropdown
          options={dropDownOptions}
          placeholder="Choose Language"
          search
          selection
          fluid
          allowAdditions
          value={currentValue}
          onAddItem={handleAddition}
          onChange={handleChange}
        />
      );
    };
    
    
    export default DropDownWithHooks;
    

    Working Sandbox