-1

I want a function to be called when the user selects an option from the Dropdown Search Selection used by @fluentui/react-northstar.

import React from 'react'
import { Dropdown } from '@fluentui/react-northstar';

class someComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        inputItems: [
            'Robert Tolbert',
            'Wanda Howard',
            'Tim Deboer',
            'Amanda Brady',
            'Ashley McCarthy',
            'Cameron Evans',
            'Carlos Slattery',
            'Carole Poland',
            'Robin Counts',
          ]
    }
  }

  onBlurHandler(){
    //Handles onBlur of Dropdown
  }

  **FUNCTION TO BE CALLED WHEN USER SELECTS THE OPTIONS FROM INPUTITEMS**
  optionSelectedHandler() {
  }

  render() {
    return (
      <div>
        <Dropdown
            search
            items={this.state.inputItems}
            onBlur={this.onBlurHandler}
            placeholder="Start Typing"
        />
      </div>
    );
  }
}
export default someComponent;

Can anyone provide the attribute which is to be used for handling the optionSelectedHandler function?

2 Answers2

0

You have to convert it to a Controlled Component.

First, you need to create a new attribute in the state to handle the selectedOption.

Then, you need to add it a value prop, and then add a onChange prop, this one should be you optionSelectedHandler.

maxpsz
  • 431
  • 3
  • 9
0

As was answered by @maxpsz, you should pass your function to the onChange prop. Unfortunately this is poorly documented, but a little experiment shows that this function receives this object:

{
 items: Array(9)
 placeholder: "Select your hero"
 onChange: ƒ optionSelectedHandler() {}
 align: "start"
 clearIndicator: Object
 itemToString: ƒ itemToString() {}
 itemToValue: ƒ itemToValue() {}
 list: Object
 position: "below"
 toggleIndicator: Object
 triggerButton: Object
 searchQuery: "Tim Deboer"
 open: false
 highlightedIndex: 2
 value: "Tim Deboer"
}

in its second argument.

So you can write your component with the selection handler like this:

const DropdownExample = () => {
  const [selectedItem, setSelectedItem] = useState("");

  function optionSelectedHandler(alwaysNull, data) {
    setSelectedItem(data.value);
  }

  return (
    <>
      <Dropdown
        items={inputItems}
        placeholder="Select your hero"
        onChange={optionSelectedHandler}
      />
      <p>You selected: {selectedItem}</p>
    </>
  );
};

You can see a working example in this sandbox.

Having said all that, I think there are much better React component libraries out there. This one has the API that is awkward, ugly, and poorly documented.

tromgy
  • 4,937
  • 3
  • 17
  • 18