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

React - Issue with state not being updated accurately

My current project involves using the <Select> component from Material-ui to create a drop-down menu. I need to update the state of the <Select> component after a selection has been made. To achieve this, I have set the value property of the & ...

Loading the Facebook JavaScript SDK asynchronously using React and Redux

I have a process that involves loading a JavaScript SDK, which looks like this: class Facebook{ constructor(){ window.fbAsyncInit = () => { FB.init({ appId : 'myappID', ...

Focusing on a specific image using Jquery

I am looking to specifically target the image within the "hero1project3" class, however, the image is currently set as a background. Is there a way in jQuery to apply effects like blur only to the image itself, for example, using ".hero1project3 img"? HTM ...

Is the array State not setting properly in React Native?

I apologize for the strange request, but I need help with a validation method for form inputs within a modal. Currently, I am checking each this.state.variable and pushing them to an aux array, which is then supposed to be set to the original fieldErrors ...

What is the best method for resetting a flexbox item?

I'm trying to achieve a layout with flex box where the first item spans 100% width, the second item is centered at 50% on its own line, and the third and fourth items each take up 50% width on the same line. Usually, clearing works fine on simple blo ...

Triggering a click event on various instances of a similar element type using the onclick function

Hey there, I'm a newcomer to Javascript. I've been practicing my Javascript skills and trying to replicate something similar to what was achieved in this example: Change Button color onClick My goal is to have this functionality work for multip ...

Creating efficient computed properties in React: a step-by-step guide

Currently, I am facing an issue with creating a table that contains checkboxes. This problem is quite frustrating, as demonstrated in the following example: I have a list of items in the format {id, value}. For each item, I generate a div element containi ...

What could be causing getStaticProps to receive an incorrect slug value?

Currently, I am encountering an issue with obtaining the correct slug in getStaticProps(). My goal is to retrieve the translated slug for a specific page (for example: the about page). The getStaticPaths() function is able to generate the correct object. ...

Material UI - sending an icon as a property

I need help with inserting a material-ui icon into my component using props. Can you please advise on what I might be doing wrong? I am struggling with passing the icon down in JSX, and here is the attempt that is not working: This code snippet shows me t ...

Error encountered by React context: TypeError - Attempting to iterate over an object that is not iterable (unable to access property

I'm encountering this error: TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) whenever I attempt to handle state using useContext. The purpose here is to initialize "tokens" as an empty array [] on page load, and then ...

Instead of scrolling through the entire window, focus on scrolling within a specific HTML element

I currently have the following elements: #elementA { position: absolute; width: 200%; height: 100%; background: linear-gradient(to right, rgba(100,0,0,0.3), rgba(0,0,250,0.3)); z-index: 250; } #containerofA { position: fixed; ...

`Erase content from a field once text is typed into a different field`

I have a Currency Converter with two input fields and a button. I enter the amount to be converted in the first field, and the result of the conversion appears in the second field. My question is: How can I automatically clear the second field when I type ...

What methods can I implement to prevent my boxes from becoming stretched out?

How can I prevent this box from stretching too much? Here is the code snippet along with the output: CSS: .social { padding-left: 1000px; border: 5px inset black; margin: 4px; width: 100px; } HTML: <div class="social"> <p& ...

Identifying the presence of a CSS class in order to add styling to a different element

Looking for help with CSS: /* targeting laptops */ @media only screen and (pointer:fine) and (max-device-height: 620px) { #root:has(.projects) ~ body { overflow: auto; /* allow scrolling */ } } My desired outcome is to set overflow: auto o ...

Error TS2694 is being caused by Electron Typescript Material-UI withStyles because the namespace "".../node_modules/csstype/index"" does not have an exported member called 'FontFace'

While I am experienced with Material-UI, I am relatively new to Electron and using React, TypeScript, and Material-UI together. Recently, I encountered an error while attempting to create an electron boilerplate code for future project initialization. Init ...

Image expansion

I have a container element div that holds various content of unknown length. How can I add a background image that extends the entire length of the container since background-images do not stretch? I attempted to use a separate div with an img tag inside. ...

Tips for making a React/Socket.IO app accessible from external sources

Trying to get my React app (built with Node.js and Socket.IO) running locally and accessible from external sources has been a challenge for me. I've managed to expose port 3000 using ngrok tunneling, but my socket connection is listening on port 3001. ...

What is the best way to ensure a "child" div does not overflow on its own and instead utilizes the padding of its parent div for rendering?

Initially, here are my code snippets: In the HTML file: <div class="div parent"> Title <div class="div child"> <div class="overflowed"> </div> </div> </div> CSS Styling: .div { border: 1px solid #0000 ...

I am having trouble styling a pre-existing class in bootstrap using my custom CSS file

html <section id="title"> <div class="container-fluid"> <!-- Nav Bar --> <nav class="navbar navbar-expand-lg navbar-dark"> <a class=" navbar-brand">tindog</a> ...

Transforming Material UI into a class-based component

How can I transform a React function into a class? I'm having trouble understanding how to adjust const { classes } = props; in a function to work within a class. You can find an example button function from Material UI here: import React from &apos ...