简体   繁体   中英

How to create a filter dropdown using React.js?

How can I implement logic for filter dropdown?

In the application is page when we can manage users, like: create, edit, remove and show. Also there is option to disable user.

There is Table for Users, on which I need to implement filter.

I need to filter by users which are "Active" that mean they have property disable: false. And "Deactive" users which have disabled: true

Here is how my Filter dropdown array looks:

 const statusOptions = [
  {
    key: 'all',
    text: 'All',
    value: 'all'
  },
  {
    key: 'disabled',
    text: 'Active',
    value: false
  },
  {
    key: 'disabled',
    text: 'Deactive',
    value: true
  }
]

 <Form.Dropdown
    label="Filter by Status"
    name="disabled"
    selection
    onChange={this.handleFieldChange}
    value={disabled || 'all'}
    fluid
    options={statusOptions}
 />

Handle Field Change function:

 handleFieldChange = (e, { name, value } = {}) => {
const { onChange } = this.props
this.setState((current = {}) => {
  const next = {
    ...current,
    [name]: value
  }
  onChange && onChange(next)

  return next
})
}

Any idea how to organize this filter logic on correct way?

The code you have posted is a little confusing, but I think what you need is the ability to update your view depending on whether a specific user is enabled or disabled.

The original array of users is presumably injected into the component as a prop; I assume that each of these users has an "enabled" property which is set to 'enabled', 'disabled' or 'all'. I'm also assuming that you somehow iterate over this list to build your UI, specifically something like:

<ul>
    { this.users.filter((user) => user.state === this.filterState)
      .map((relevantUser) => {
           return (
                <User {..relevantUserProps}>
           )
      })
    }
</ul>

So your handleChange callback simply needs to set the filterState of the component:

handleFieldChange = (event) => {
    const newFilterState = this.statusOptions.find((option) => option.text === event.target.value)).key
    this.setState({
        filterState: newFilterState,
    })

Clearly this logic might not exactly fit your component, but hopefully you get the gist. Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM