Created
May 5, 2019 09:39
-
-
Save sbeugen/a22d616700156db489493492074f7176 to your computer and use it in GitHub Desktop.
Custom select component using only build in React hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* global $ */ | |
| import React, { useEffect, useRef, useCallback } from "react"; | |
| const CustomSelect = ({ value, name, placeholder, onChange, options, errorMessage }) => { | |
| const elementRef = useRef(null); | |
| const showPopover = useCallback( | |
| () => { | |
| if (errorMessage) { | |
| $(elementRef.current) | |
| .popover({ | |
| content: errorMessage, | |
| template: | |
| '<div class="popover" role="tooltip"><div class="arrow"></div><div class="popover-body"></div></div>' | |
| }) | |
| .popover("show"); | |
| } | |
| }, | |
| [errorMessage] | |
| ); | |
| const hidePopover = useCallback(() => { | |
| $(elementRef.current).popover("hide"); | |
| }, []); | |
| useEffect( | |
| () => { | |
| const element = elementRef.current; | |
| if (element) { | |
| element.onfocus = showPopover; | |
| element.onblur = hidePopover; | |
| } | |
| if (!errorMessage) { | |
| hidePopover(); | |
| } | |
| }, | |
| [errorMessage, showPopover, hidePopover] | |
| ); | |
| return ( | |
| <select | |
| style={{ borderBottom: `1px solid ${errorMessage ? "red" : "blue"}` }} | |
| name={name} | |
| value={value} | |
| onChange={onChange} | |
| ref={elementRef} | |
| > | |
| <option value="" label={placeholder} disabled defaultValue hidden /> | |
| {options.map((option, index) => ( | |
| <option value={option.value} label={option.label} key={index} /> | |
| ))} | |
| </select> | |
| ); | |
| }; | |
| export default CustomSelect; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment