Currently, I have implemented a search input box allowing users to either enter a value or select from a list of suggestions. The issue arises when the user selects an option using the tab key, as it causes the cursor to move outside the input box despite staying within when selecting with a mouse.
The code structure is as follows:
<SearchBar
<SearchInputWrapper>
<SearchInputBox>
<TextInput
placeholder="Enter Text here"
minHeight="17px"
setSearchText={handleTextChange}
paddingTopBottom="5px"
paddingLeftRight="4px"
lineHeight="1.2"/>
</SearchInputBox>
</SearchInputWrapper>
/>
const SearchInputWrapper = styled.div`
height: auto;
width: 100%;
box-sizing: border-box;
padding: 0;
align-self: stretch;
word-break: break-word;
#tags-container:not(:focus) {
height: 20px;
text-overflow: ${({ pinned }) => (pinned ? 'unset' : 'ellipsis')};
white-space: ${({ pinned }) => (pinned ? 'unset' : 'nowrap')};
}
#tags-container:focus {
height: 20px;
text-overflow: unset;
white-space: unset;
word-break: normal;
}
`;
The TextInput component handles keyDown events:
class TextInput extends Component {
constructor(props) {
super(props);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
const TAB = 9;
handleKeyDown(event) {
if (
event.which === TAB ||
(event.which === ENTER && meta) ||
(event.which === SPACE && meta)
) {
this.suggestionsList.apply();
event.stopPropagation();
event.preventDefault();
}
}
}
Despite the handleKeyDown function being overridden by the callBack function(handleTextChange), there's a need to retain focus in the input box after tab selection. A workaround attempt involved adding document.getElementsById("#id").focus(), which retains focus but places the cursor at the start of the text rather than where desired (end of the text).
const handleTextChange = useCallback(
(q) => {
e.stopPropagation();
e.preventDefault();
updateModel({
...model,
searchText: q
}
}
});
document.getElementById('input-textbox').focus();
},
[updateModel, model]
);
https://i.stack.imgur.com/rJhTW.png Seeking guidance on how to ensure the cursor remains at the end of the text in the input box upon tab key selection.