React Select auto size width

前端 未结 5 2116
闹比i
闹比i 2020-12-30 06:00

When using react-select it is not auto sizing by option value, but using width:100% as you can see in picture:

Options are short:<

5条回答
  •  失恋的感觉
    2020-12-30 06:37

    SOLUTION 1

    You can leverage React's inline styles by updating the components' width based on the length of the selected option.

    Let me explain further: Say the selected value is HelloWorld. This string is of length 10. We could guess that each character accounts for say 8px each on average (total guess I have no clue at all). Thus, the width of this word is around 8*10=80px, right ? Also, there are some controls after the word (the carret and the cross) and we need some minimum padding: together they may be of 100px width. Then here you have it: your div's width should be ( 8px * 10 letters ) + 100px = 180px.

    More precisely, the correct formula is something like:

    (average_letter_size * selected_value.length) + other_elements_sizes
    

    When selected_value changes, so does its length, and therefore the width of the div gets updated with the new total.

    Example: if the selected value is now Lorem Ipsum dolor sit amet, the length is now 26. By applying the formula we get a larger width of : (8px * 26 letters) + 100px = 308px.

    For this to work in react, here is a snippet:

    
                            
        
    提交评论

提交回复
热议问题