Prevent input from being cleared when selecting an option with React-Select

Unfortunately, there was no satisfactory solution to this question so I will provide an answer:

The issue arises when trying to utilize React-Select with a persistent input value that remains even after selection or blurring. Regrettably, this functionality is not currently built into the component, thus necessitating a workaround.

I also addressed this matter in response to one of the several discussions on this topic: https://github.com/JedWatson/react-select/issues/588
https://github.com/JedWatson/react-select/issues/3210

Answer №1

you can add to this by using this method for the desired outcome

const Component = () => {
  const [inputValue, setInputValue] = useState("");
  const [savedInput, setSavedInput] = useState("");
  
  return (
    <Select
      placeholder={savedInput} // displays when input is empty and blurred 
      value="" // always shows the placeholder
      inputValue={inputValue} // allows you to continue typing where you left off
      onInputChange={setInputValue} // enables actual typing
      onMenuClose={() => setSavedInput(inputValue)} // saves input before clearing it
      onFocus={() => {
        setInputValue(savedInput);
        setSavedInput(""); // avoids displaying undesired placeholder value
      }} 
      blurInputOnSelect  // makes above functionality possible
    />
  )
}

https://codesandbox.io/s/sharp-pike-rnjbr?autoresize=1&fontsize=14&hidenavigation=1&theme=dark

Answer №2

To effectively tackle this issue, it is recommended to manually configure the input value (manage the onInputChange() event) only during active user input.

In essence, we should override ReactSelect's default behavior of clearing the input value when losing focus, closing the menu, or selecting a value.

For instance:

export default function App() {
  const [input, setInput] = useState("");

  const options = [
    { label: "first option", value: 1 },
    { label: "second option", value: 2 },
    { label: "third option", value: 3 }
  ];

  return (
    <Select
      options={options}
      inputValue={input}
      onInputChange={(value, action) => {
        // only update the input if the action triggering the change is
        // "input-change," while disregarding others like: "set-value,"
        // "input-blur," and "menu-close"
        if (action.action === "input-change") setInput(value); // <---
      }}
    />
  );
}

https://codesandbox.io/s/relaxed-beaver-e15x0?fontsize=14&hidenavigation=1&theme=dark

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am converting a class component to a functional component within a React-Redux-Firebase project

I am currently in the process of rebuilding this component. Check out the updated code here Also, take a look at the project actions script here However, I'm facing an issue with rewriting mapStateToProps and mapDispatchToProps functions. The error ...

Reflection of three.js CSS3D sprite on the z-axis

Each CSS3D sprite within my scene displays a reflection when the camera is rotated. Is there a way to prevent this? The Reflection does not appear consistently across different browsers and operating systems - it's not visible on Firefox on Mac, but i ...

employing flush for lodash's throttle wrapper

When using TypeScript with JavaScript and Angular: I am trying to use the throttle decorator from lodash to limit an API call while a user is navigating around the page, ensuring that it fires before they leave the site. In my TypeScript constructor, I h ...

Validate fields by iterating through an object and considering three data points for each field

The struggle is real when it comes to coming up with a title for this question. Suggestions are welcomed! When it comes to field validation, I require three data elements per field: variable name, element ID, and whether it is required or not. Although I ...

Using the Jquery accordion function within google maps is limited to running only one time

After successfully creating a google maps page with markers generated from XML, I encountered an issue. The plan was to display event information in a div when a marker is clicked, along with attaching an accordion to the events data. Although the first cl ...

Production Server experiencing issues with sending Large Lists via Http Post

I'm experiencing an issue where the server is unable to read values from a large list when sent using Post. Oddly enough, this works on the homologation server but not on the production server. Http post AngularJs $http({ url: $rootScope.raiz_ws ...

Pull the Bootstrap radio value from hyperlink buttons

Is anyone else having trouble retrieving values of radio buttons using jQuery? Here are the radio buttons in question: <div class="input-group"> <div id="radioBtn" class="btn-group"> <a class="btn btn-warning radio-selector btn ...

In the world of Angular, whitespace is simply treated as non-existent when it comes

Within the controller, I have an array structured as follows: 'Pipe': '|', 'Comma': ',', 'Tab': '\t' }; When configuring ng-options in my code, it is implemented in this manne ...

Using jQuery to duplicate elements by copying and pasting

I am facing a scenario where I need to dynamically create and manipulate a div element in my web application. The process involves appending the newly created div to another container upon clicking a button, followed by triggering a series of functions on ...

Safeguard your Firebase database listeners against potential web DOS attacks and unauthorized access to sensitive credentials

Firebase is such a game-changer on mobile devices, but it's not always the best fit for web applications. This is common knowledge. I rely on firebase My users are aware of the database URL They can view certain aspects of the database that I'v ...

Incorrect font displayed on Bootstrap button after inserting hyperlink

This section contains my HTML code snippet: <div class="panel panel-default"> <div class="panel-heading"> Records <button type="button" class="btn btn-xs btn-success pull-right" id="command-add" data-row-id="1"> ...

What are the steps involved in manipulating objects within an asynchronous result object?

I'm interested in learning how to manipulate a JS object from one file into another asynchronously, as my experience with asynchronous code principles is limited. Scenario: In my app.js file, I dynamically generate 'app panels' based on ...

Browserify is having trouble locating the npm module

I'm encountering great difficulty while trying to develop an NPM module: react-smallgrid import React from 'react'; import _ from 'lodash'; export default class SmallGrid extends React.Component{ After compilation: browserify: ...

Having issues with the onclick() function not functioning properly with Jquery?

Yesterday, I successfully integrated some Jquery code into my website. However, when I attempted to add more code today for a new feature, everything seemed to stop working. Even the code that was functioning perfectly yesterday has now ceased to work. The ...

Having trouble with preventDefault() not working during a keyup event?

I am struggling to make preventDefault() function properly. Here are a few variations of the code that I have attempted: First: $(document).keyup(function (evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode == 192) { ...

Even though credentials are provided, req.user remains undefined within passportjs

After successfully authenticating through Google, I'm facing an issue where the user information is not being sent from the frontend to the backend, even with credentials included. I suspect it may be a same site problem, but I am unsure of how to res ...

Oops! Looks like there's an issue with reading the property 'value' of undefined in React-typeahead

Having some issues with setting the state for user selection in a dropdown menu using the react-bootstrap-typeahead component. Any guidance or resources on this topic would be highly appreciated. Details can be found here. The function handleAddTask is su ...

Unique React Router Custom Prompt: Only one prompt can be supported by a single history object

I have developed a custom React Router Prompt to alert users when attempting to navigate to another page without saving their data. Despite everything functioning correctly, I am encountering an irritating warning: Warning: A history supports only one pro ...

Issue encountered: Inability to implement asynchronous functionality within a forEach loop while making an API request

When making a GET API call, the code looks like this router.get('/review', async (req, res) => { try { const entity = await Entity.find(); const entityId = []; Object.keys(entity).forEach((key) => { entityId.push(entity[ ...

`What purpose does the data-view attribute serve in Durandal JS?`

While experimenting with the Durandal JS starter kit application, I happened to view the page source in Mozilla browser and noticed the following. <div class="" data-view="views/shell" style="" data-active-view="true"> </div> I couldn't ...