skip to Main Content

So I have custom select input which contains menu items(list of selectable items). Right now when we click on the select input it opens a drop down menu displaying the first 10 items(visible items = 10). I have done this using following css :-

style={{ maxHeight: `${visibleItems ? `calc(1.5rem * ${visibleItems}` : 'auto'}`, ...style }}

Suppose I have selected item no. 12 the drop down menu will still show the first 10 items only even if the 12th item is selected. I want to implement it such that visible list of items contains the one which is selected before. I want to have a similar behaviour to react-select component which you can find here https://react-select.com/home .

I would be glad if anyone can help me with a few suggestions on how I can proceed with it. I cannot paste the complete code here due to some restrictions, but I would be really thankful if anyone could help me out.

3

Answers


  1. Chosen as BEST ANSWER

    I found the answer which I was looking for. You can just use scrollIntoView() method to scroll to the particular item in the menu when the menu is opened in the select input. You can call it using the ref of the active item.

     activeItemRef.current.scrollIntoView();
    

  2. You need 2 states. One for visible items which you have used. Another one is when an item is selected. Then you can extend your if statement to check if there is a selected item, there is no need to show this height. And consider, this second state can contain an id related to the selected item. So you can filter it out to display just it.

    If you could show me the codes, I could help you in the codes.

    Login or Signup to reply.
  3. If all of your items are stored in an array, the best way to make would be to use the Array.prototype.sort() function and obviously it sort all the elements of an array without changing it size.
    It accept a custom function as a parameter to compare the element like this:

    function compareFn(a, b) {
        if (a is less than b by some ordering criterion) {
            return -1;
        }
        if (a is greater than b by the ordering criterion) {
            return 1;
        }
    }
    

    In your case you can put a function to check is the item was selected or not then it will display your selected item first in your list.
    Hope this help.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search