[6/1 TIL] react-select 라이브러리 이용하기

kind J·2022년 6월 1일
1
post-thumbnail

form Submit 이벤트가 일어날 때 selectbox 의 선택된 값을 보내고 싶어서 'react-select' 라이브러리를 사용해보았다.

1) react-select 설치

yarn add react-select

2) import

import Select from 'react-select'

3) 사용하기


const codeOptions = [
	{ value: 'ALL', label: 'ALL' },
  	{ value: 'A', label: 'A' },
  	{ value: 'B', label: 'B' },
]

const colourStyles = {
  control: (style: any, { isFocused }: any) => ({ //current
    ...style,
    border: isFocused ? '1px solid #DDCEF5' : '1px solid #ebebeb',
    boxShadow: 'none',
    backgroundColor:'none',
    outline: 'none',
    color: "#ebebeb",
    width: 100,
    
  }),
  option: (style: any, { isFocused }: any) => { //option
    return {
      ...style,
      backgroundColor: isFocused ? '#DDCEF5' : null,
      color: "#333333",
      width: 100,
    }
  },
  singleValue: (base: any) => ({ 
    ...base,
    color: "#ebebeb" //current color
  }),
}

const Search = () => {
  	const [selectCode, setSelectCode] = useState('ALL')
    const handleSelectChange = (e: any) => { 
      setSelectCode(e.value)
    }
	return (
		defaultValue={codeOptions[0]}
        options={codeOptions}
        styles={colourStyles}
        theme={(theme) => ({
          ...theme,
          borderRadius: 8,
        })}
        onChange={handleSelectChange}
	)
}
export default Search

handleSelectChange 함수에 e 객체의 타입을 명시해줘야 하는데
ChangeEvent 를 넣으면 오류가 났다. 임시방편으로 any 로 해놨는데.. 검색해봐도 무슨 타입인지 안나온다..ㅠㅠ
지금은 시간이 없어서 넘어가지만, 시간이 좀 생기면 라이브러리를 한번 뜯어 봐야겠다.

profile
프론트앤드 개발자로 일하고 있는 kind J 입니다.

0개의 댓글