Skip to content

Instantly share code, notes, and snippets.

@sbeugen
Created May 5, 2019 09:39
Show Gist options
  • Select an option

  • Save sbeugen/a22d616700156db489493492074f7176 to your computer and use it in GitHub Desktop.

Select an option

Save sbeugen/a22d616700156db489493492074f7176 to your computer and use it in GitHub Desktop.
Custom select component using only build in React hooks
/* 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