1

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?

1 Answer 1

3

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} ... />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.