Search code examples
javascriptreactjsrefactoringsemantic-ui

Refactor dropdown component in React


I have to use multiple dropdowns from semantic-ui-react in my project. They need to have different props. It looks like this

 <div className="wrapper">
        <img className="icon" src={iconA} alt="iconA"></img>
        <h1>A</h1>
        <Dropdown
          className="dropdown"
          search
          selection
          options={optionsA}
          placeholder="A"
          defaultValue="A"
          onChange={handleAChange}
        />
 </div>
 <div className="wrapper">
        <img className="icon" src={iconB} alt="iconB"></img>
        <h1>B</h1>
        <Dropdown
          className="dropdown"
          search
          selection
          options={optionsB}
          placeholder="B"
          defaultValue="B"
          onChange={handleBChange}
        />
 </div>

I want to refactor this and create a single component for this by pasing different props. Please guide me on how this can be refactored in the best way possible.


Solution

  • First, create your custom dropDown component and extract props using object destructuring, you can give deafult values to props there itself, but better use PropTypes for that.

    const CustomDropDown = (props) => {
      const { 
        className,
        search,
        selection,
        options,
        placeholder,
        defaultValue,
        onChange
      } = props;
    
      return (
        <div className="wrapper">
          <img className="icon" src={iconA} alt="iconA"></img>
          <h1>A</h1>
          <Dropdown
            className={classname}
            search={search}
            selection={selection}
            options={optionsA}
            placeholder={placeholder}
            defaultValue={defaultValue}
            onChange={onChange}
          />
        </div>
      )
    }
    

    Now, call the component like this,

    <CustomDropDown 
      className="dropdown"
      search
      selection
      options={optionsA}
      placeholder="A"
      defaultValue="A"
      onChange={handleAChange}
    />