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:
getOptions() {
return [
{ value: 'AND', label: 'AND' },
{ value: 'OR', label: 'OR' }
]
}
And code which produces it:
<Select
options={this.getOptions()}
value={value}
autosize={true}
clearable={false}
simpleValue
/>
Is there any way to make react-select
to show these values with auto sizing, so select box would be the same as option length, and I could, for example, center this select box in <div>
?
Updated 14.11.2017 Full example can be seen in this jsFiddle
Update: for people who are using React-Select for a "tags autocomplete" feature but are having trouble where it sets a style width that is too narrow based on the previous tag you searched, this is what works for me:
Set a style of:
Set
classNamePrefix="myCustomPrefix"
in the component (docs).Old answer:
See the official docs at https://react-select.com/styles#style-object
I originally thought that setting
width
to "auto" foroption
worked for me:Inline styles did not work for me. I just wrapped the Select component in a div and gave the div the width I wanted.
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 length10
. We could guess that each character accounts for say8px
each on average (total guess I have no clue at all). Thus, the width of this word is around8*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 of100px
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:
When
selected_value
changes, so does itslength
, 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 now26
. 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:
As you can see I added :
to your component. Whenever the state gets updated, everything is propagated including the width of the component.
See a working example in this fiddle.
Eventually, you want to fine-tune the rules and averages to your needs. I also suggest you apply a letter size depending on the number of capital and lowercase letters in the selected value.
SOLUTION 2 (edit)
I came up with a pure CSS solution if you want. It should be better tested against your design, but this should work:
See a working fiddle (I changed some of the examples for better illustration)
Tell me what you think. :)
if you're using react-select v3 you can use customStyles object: