react-tag-input-component
react-tag-input-component copied to clipboard
Change `focus` to `input` tag
trafficstars
I need change a focus to input tag when div with rti--container class clicked. I think that's more better .
A workaround could be to wrap the component in another element, then watch the click event on it to focus the inner input...
<div
id={id}
onClick={() => (document.querySelector(`#${id} .rti--input`) as HTMLInputElement).focus()}
>
<TagsInput
value={selected}
onChange={setSelected}
/>
</div>
Ideally, this lib would expose the ref from the inner input for this kind of thing.
Here is a fully working (as Id expect UX-wise, anyway) solution. It uses onMouseDown instead of onClick because onMouseDown is fired before any blur event, so will allow the input to always retain focus. YMMV but Ive logged the interaction events and it all seems to work as expected:
const EmailsInput = () => {
const [selected, setSelected] = useState([]);
const wrapperRef = useRef(null);
const handleWrapperClick = e => {
const wrapperEl = wrapperRef.current;
if (!wrapperEl) {
return;
}
const rtiContainerEl = wrapperEl.querySelector(".rti--container");
const rtiInputEl = wrapperEl.querySelector(".rti--input");
if (!rtiInputEl) {
return;
}
// Prevent default so that the input doesn't lose focus, if the mousedown
// event occured on the RTI container el wrapped by our outer wrapper el.
if (e.target === rtiContainerEl) {
e.preventDefault();
}
// Focus the input. If it was previously focused it will retain focus.
rtiInputEl.focus();
};
return (
<div ref={wrapperRef} onMouseDown={handleWrapperClick}>
<TagsInput
value={selected}
onChange={setSelected}
name="Email Addresses"
placeHolder="Add Email Address..."
isEditOnRemove={true}
separators={
[
"Enter",
"Tab",
",",
" "
]
}
/>
<div className="flex flex-row justify-end text-xs text-zinc-500 mt-2">
<em>Press "return" or "enter" to add new emails.</em>
</div>
</div>
);
};
Bless.