downshift-js / downshift

🏎 A set of primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components.
http://downshift-js.com/
MIT License
12.05k stars 933 forks source link

Clear Selection via an external button click #480

Closed preraksola closed 6 years ago

preraksola commented 6 years ago

What you did: I have integrated downshift in a form in my react application to display a list of users fetched from an API. I have a button in this form, which is used to clear all the fields. However, I am not able to clear the autocomplete text field of Downshift upon clicking the button.

So, is there a way that I can use the clearSelection method in another function?
If not, is there any other alternative?

Thank you.

geeofree commented 6 years ago

Hi! :wave: Perhaps we can make Downshift have a ref callback prop that gets called inside the cDU with Downshift as an argument to it? Something like this:

class Downshift extends Component {
  // Downshift Stuff...
  componentDidMount() {
    const {ref} = this.props
    if (ref && typeof ref === 'function') {
      ref(this)
    }
  }
  // ...Other Downshift stuff
}

That way we can use Downshift's various methods on stateful components like this:

class MyForm extends Component {
  setDownshift = (downshift) => {
    this.downshift = downshift
  }

  resetForm = (e) => {
    ...Your reset logic here
    this.downshift.clearSelection()
  }

  render() {
    return (
      <form>
        {/* Form stuff goes here */}
        <AutoComplete ref={this.setDownshift} />
        <button onClick={this.resetForm}>Reset</button>
      </form>
    )
  }
}

function AutoComplete(props) {
  return <Downshift ref={props.ref}>{AutoCompleteLayout}</Downshift>
}

What do you think?

kentcdodds commented 6 years ago

You can do that already. That's how refs in react work. No need to change the code.

That said, it would be very imperative so it'd probably be better to do this a different way.

If you want to control the selectedItem state outside downshift, the solution is to use control props. See the documentation for how to accomplish that. There's also an example for this as well.

Either way, this is definitely possible, so I'll go ahead and close this issue. Thanks!

ChrisPlease commented 5 years ago

@kentcdodds that example link 404's. Has the example been moved? I have two downshift components in one form, and I'd like to clear the second when the first value changes. Struggling to figure out how to do that.

kentcdodds commented 5 years ago

Here's a permalink: https://github.com/paypal/downshift/blob/e1273c8df4d6b33365d8f2bf69cee9d6f8b97760/stories/examples/controlled.js

aysegulkavakli commented 1 year ago

Is there any solution with React function components and/or can we use the clearSelection method outside of the downshift ?