Searene
Searene

Reputation: 27544

Programmatically select an item in Dropdown in Semantic-UI-React

I created a Dropdown list using Semantic-UI-React to let the user select colors.

enter image description here

The code is as follows.

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

const colorOptions = [{
  text: 'red',
  value: 'red'
}, {
  text: 'blue',
  value: 'blue'
}, {
  text: 'custom',
  value: 'custom'
}];

const Foo = () => (
  <Dropdown
    placeholder='color'
    search
    selection
    options={colorOptions} />
)

export default Foo

Suppose that the current selected color is red. Now the user clicks on custom. Then a dialog will show`` up with more colors. And there are two buttons in the dialog. OK and Cancel.

What I want is that, when the user clicks on Cancel, the selected color would revert back to the previous one, red, instead of custom. Could it be done with Semantic-UI-react?

Upvotes: 1

Views: 4849

Answers (1)

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

You can use state for that.

I'm assuming you have another component that is rendering your Foo component (since you paste its code as a stateless function)

  1. Use onChange in your Dropdown component, so you keep track of the current value. Should you need more info about how onChange works check their docs.

For example:

const Foo = (onChange, value) => (
  <Dropdown
    placeholder='color'
    search
    selection
    options={colorOptions}
    onChange={onChange}
    value={value}
  />
)
  1. on every onChange, save this value on state and also keep a copy of the previous value. Since setState is asynchronous you can easily do this as:

Example:

handleChange(event, data) {
  this.setState(prevState => ({
    previousValue: prevState.value,
    value: data
  }))
}
  1. When you click "Cancel" button simply revert the Dropdowns's value to the previous one.

Example:

onCancel() {
  this.setState(prevState => ({
    value: prevState.previousValue
  }))
}
  1. on render always pass value to Foo component

Example:

<Foo onChange={handleChange} value={this.state.value} ... />

Upvotes: 3

Related Questions