Prevent the cursor from exiting the div element when the tab key is pressed

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.

Answer №1

In order to prevent a certain behavior using event.preventDefault(), you should include the following code snippet:

<TextInput
  placeholder="Enter Text here"
  minHeight="17px"
  paddingTopBottom="5px"
  paddingLeftRight="4px"
  lineHeight="1.2"
  onKeyDown={(event) => {
    if (event.key === "Tab") {
      event.preventDefault();
    }
  }}
/>

To ensure that the action is only prevented when the tab key is pressed, add an onKeyDown event listener to the TextInput component.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reactive Popover reactstrqp and state management issues

Here I am utilizing an uncontrolled popover from reactstrap. Within this popover, there is a list of categories and an edit button option. When the edit button icon is clicked, the popover appears. However, an issue arises where the popover opens at the ...

Is there a way to incorporate the MUI theme color into inline styles?

Imagine I have the following tabs displayed below. Is there a way to implement MUI's primary and secondary colors for inline CSS? My goal is to personalize the colors using my own palette. <Tabs value={value} ...

What is the best way to control the scroll position of a React Material-UI component when clicking a button?

I'm facing a challenge with creating custom buttons to navigate through a long list of images within a parent element window that acts as a viewer. While I can set the parent element to scroll, managing the state for click events has proven to be tric ...

Prevent jQuery UI default styling from being applied

I'm curious about how to prevent jQuery UI from adding any classes when initializing $.tabs(). This is the structure of my HTML: <link href="smoothness/jquery-ui-1.8.20.custom.css" rel="stylesheet" type="text/css" /> ... <link href="estilos ...

A guide on effectively utilizing ref forwarding in compound component typing

I am currently working on customizing the tab components in Chakra-ui. As per their documentation, it needs to be enclosed within React.forwardRef because they utilize cloneElement to internally pass state. However, TypeScript is throwing an error: [tsserv ...

Position the div in the center, but for smaller sizes, switch to aligning

My current layout setup is as follows: Left side bar with a width of 200px and positioned at left: 0; Center section with a width of 700px and positioned at left: 250px; Right side bar with a width of 200px and positioned at right: 10px; While this arra ...

Pressing the button does not switch the component state (when the button and component are located in separate files)

Here is the code snippet of my layout: import Menu from "./Menu"; import ButtonMenu from "./ButtonMenu"; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en" ...

What are the potential downsides of using ID to access HTML elements in React TypeScript?

During my previous job, I was advised against accessing HTML elements directly in React TypeScript using methods like getElementById. Currently, as I work on implementing Chart.js, I initially used a useRef hook for setting up the chart. However, it appear ...

Is it feasible to place an image on top of a box?

Hello everyone, I have been trying to figure out how to achieve a specific layout in React. I am using MUI so there is no need for any hard-coded CSS. However, my attempts have not been successful so far. The layout I am aiming for consists of an image on ...

Having trouble retrieving the necessary data to generate a menu, the getStaticProps function is coming back as undefined

I'm currently working with Next.js 13 & Strapi, and my goal is to create a Menu component utilizing the getStaticProps function. To achieve this, I've implemented a Layout component within the _app.js file, and nested a Menu component inside the ...

Tips on personalizing MUI X Data Grid Toolbar to exclusively display icons

`function EnhancedToolbar() { return ( <GridToolbarContainer> <GridToolbarIcon icon={<FilterListIcon />} /> <GridToolbarIcon icon={<ViewColumnIcon />} /> <GridToolbarIcon icon={<SettingsEthernetIc ...

Correct placement of elements using absolute positioning and optimized scroll functionality

I am currently working on implementing tooltips for items within a scrollable list. My goals for the tooltips are as follows: Ensure they are visible outside and not restricted by the scroll area Appear immediately after the corresponding item Be detach ...

Restricting the number of lines within a paragraph in Angular 2

Is there a method to limit the number of lines in a <p> tag and add an ellipsis (...) at the end? Using character count for truncation doesn't work well as the width of the element varies according to device screen size. ...

Errors are not being shown on mandatory fields in the form

After watching a tutorial video, I attempted to create a sign-up form. However, despite following all the steps, I encountered an issue where the Surname and Given name fields, which I set as required fields, were still processing blank when the form was s ...

Is it necessary to have uniform spacing between links in a responsive navigation menu?

I am attempting to create a horizontal menu navigation system. I have multiple links in the navigation, and my goal is to evenly space them horizontally. Is there a way to achieve uniform spacing between links in a horizontal menu? HTML: <div id= ...

Having trouble saving the server-sent cookie on the browser. Employing Axios on the client side

Here is my express code where I am utilizing express-session to manage storage and work with cookies. Since version 1.5.0, the module no longer requires cookie-parser to handle storing the cookie in req/res. The session data is stored in a PSQL database h ...

Ways to eliminate header and footer data while printing a webpage

In my attempt to implement the code displayed below, I am encountering an issue where the header and footer continue to appear on the printed page. Despite numerous attempts with various CSS elements, I have been unsuccessful in removing the header and fo ...

The confirm() function shows up before the background on a blank layout

I'm facing an issue where whenever my confirm() function pops up, the alert box displays correctly but then the background turns blank. I've tried various solutions like moving the entire if statement to the bottom of the page or at the end of th ...

exchange the class using only JavaScript

I need help with a code snippet that allows for swapping classes using a loop. The objective is to click on the brown square causing it to move to the position of the blue square, while the blue square moves to the previous position of the brown square. T ...

Any recommendations besides suggesting "g"? Let's brainstorm some other ideas for g!

Looking for some assistance with a mixin I wrote that seems to be causing a loop. Any suggestions on how to optimize the code or alternative methods to achieve the desired outcome? <div class='mh-60 pt-10'>dfgdfgsdfgsdf</div> ...