1- import { useState , useRef , useEffect } from 'react'
1+ import { useState , useRef , useEffect , useLayoutEffect , useMemo } from 'react'
22import cn from 'classnames'
33import { DropdownMenu } from '../DropdownMenu'
44import styles from './Dropdown.module.scss'
@@ -14,19 +14,42 @@ export namespace Dropdown {
1414 value : T
1515 onChange : ( value : T ) => void
1616 className ?: string
17- max_width ?: number
1817 }
1918}
2019
2120export const Dropdown = < T extends string > ( {
2221 options,
2322 value,
2423 onChange,
25- className,
26- max_width
24+ className
2725} : Dropdown . Props < T > ) => {
2826 const [ is_open , set_is_open ] = useState ( false )
2927 const dropdown_ref = useRef < HTMLDivElement > ( null )
28+ const button_ref = useRef < HTMLButtonElement > ( null )
29+ const [ width , set_width ] = useState < number > ( )
30+
31+ const longest_label = useMemo (
32+ ( ) =>
33+ options . reduce (
34+ ( longest , option ) =>
35+ option . label . length > longest . length ? option . label : longest ,
36+ ''
37+ ) ,
38+ [ options ]
39+ )
40+
41+ useLayoutEffect ( ( ) => {
42+ if ( button_ref . current && longest_label ) {
43+ const canvas = document . createElement ( 'canvas' )
44+ const context = canvas . getContext ( '2d' )
45+ if ( context ) {
46+ const button_style = window . getComputedStyle ( button_ref . current )
47+ context . font = button_style . font
48+ const text_width = context . measureText ( longest_label ) . width
49+ set_width ( text_width + 40 )
50+ }
51+ }
52+ } , [ longest_label ] )
3053
3154 const selected_option = options . find ( ( opt ) => opt . value === value )
3255
@@ -55,7 +78,7 @@ export const Dropdown = <T extends string>({
5578 }
5679 } ) )
5780
58- const style = max_width ? { maxWidth : `${ max_width } px` } : undefined
81+ const style = width ? { width : `${ width } px` } : undefined
5982
6083 return (
6184 < div
@@ -64,6 +87,7 @@ export const Dropdown = <T extends string>({
6487 style = { style }
6588 >
6689 < button
90+ ref = { button_ref }
6791 className = { styles . button }
6892 onClick = { ( ) => set_is_open ( ! is_open ) }
6993 data-is-open = { is_open }
@@ -77,9 +101,7 @@ export const Dropdown = <T extends string>({
77101 ) }
78102 />
79103 </ button >
80- { is_open && (
81- < DropdownMenu items = { menu_items } className = { styles . menu_override } />
82- ) }
104+ { is_open && < DropdownMenu items = { menu_items } /> }
83105 </ div >
84106 )
85107}
0 commit comments