Troubleshooting hover conflicts and enter events in ReactJS autocomplete functionality

Trying to enhance my learning, I am currently working on developing an autocomplete feature. Referencing this example for guidance:

https://codesandbox.io/s/8lyp733pj0.

Encountering two main issues with this implementation:

1.) Conflict between mouse hover and keypress. When using the keyboard to navigate through the list, the active item gets highlighted. Simultaneously, if using the mouse, another item may get highlighted resulting in multiple selections.

2.) Upon selecting an item by pressing enter, the input field correctly fills with the selected text. However, upon pressing enter again, it changes the text back to the index 0 item instead.

Seeking assistance in resolving these dilemmas. Already experimented with hover and focus in CSS but without achieving desired results.

Potential solutions under consideration:

  • Disabling mouse events when a keyboard is being used, and vice versa.
  • Considering removing this.setState({activeSuggestion: 0}) for the enter event.

Appreciate any help provided - grasping the nuances of state management with React is proving to be quite challenging.

Answer №1

  • The function onKeyDown is successfully updating the value of activeSuggestion. It would be beneficial to incorporate a scroll feature in the select element when activeSuggestion is not visible.
  • In my view, it is necessary to update the value of activeSuggestion using the onMouseEnter function.
  • Remember to eliminate line 32 from styles.css which targets .suggestions li:hover when making these changes.

It's important that only the element with .suggestion-active has the active styles and not the ones that are hovered over. The goal is for the onMouseEnter function to update the value of activeSuggestion.

  • Here is the code snippet:
// Autocomplete.jsx

// Add this after function onKeyDown on line 84:
  onMouseEnter = e => {
    try {
      e.persist();
      const currentIndex = parseInt(e.target.dataset.index, 10);
      this.setState({ activeSuggestion: currentIndex });
    } catch (reason) {
      console.error(reason);
    }
  }


// Then, define const onMouseEnter after the render() method:
  render() {
    const {
      onChange,
      onClick,
      onKeyDown,
      onMouseEnter,
      state: {
        activeSuggestion,
        filteredSuggestions,
        showSuggestions,
        userInput
      }
    } = this;

// In the li nodes (line 123), include props onMouseEnter and data-index like so:
        <li
          className={className}
          key={suggestion}
          onClick={onClick}
          onMouseEnter={onMouseEnter}
          data-index={index}
        >
          {suggestion}
        </li>
  • Don't forget to remove line 32 from styles.css targeting .suggestions li:hover.

I hope this explanation is useful.

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

Enhance your text with personalized logos using autocomplete

Do you know if there is a way to include icons with autocomplete text suggestions? I have successfully implemented the autocomplete text using adapters, but I would like to add icons to make it more visually appealing. Any suggestions on how to achieve t ...

The error message "Cannot read property 'push' of undefined" is displayed when trying to access this.props.history.push

I've looked through numerous solutions, yet I'm still encountering this error. import JobListing from './JobListing.jsx'; import createHistory from "history/createBrowserHistory"; const history = createHistory();` handleSubmit(event) ...

JavaScript situation

Need some assistance with my code. I'm trying to display a div when the visibility class is set to visible, but it's not working as expected. Can someone help me troubleshoot this issue? CSS: #nor1 {position:absolute;top:100px;left:100px;z-inde ...

The rangeslider thumb is positioned incorrectly on the track in the Firefox browser. How can this issue be resolved? Please see the code provided

Hey there, I am currently facing an issue with the compatibility of a range slider on different browsers. While it works perfectly on Chrome and Safari, Mozilla browser does not seem to support it. I have been trying my best to resolve this problem witho ...

Resetting several sticky titles after displaying and hiding elements

Inspired by a popular codepen example, I have successfully implemented sticky titles in my sidebar. However, when integrating these sticky titles with the functionality to show/hide related items on click, I encountered some unexpected issues. The code sni ...

How can I create a reverse animation using CSS?

Is there a way to reverse the animation of the circular notification in the code provided? I want the circle to move forward, covering up the info and fading out. I've tried switching the animation around but haven't had success. Any suggestions? ...

styling CSS to achieve equal heights for div alignments

On my webpage, I have two sections that are not aligned in height or centered. How can I center these sections in the middle of the page with the same height alignment? One section is a profile section and the other contains photos of the profile, but they ...

A step-by-step guide on masking (proxying) a WebSocket port

Within my server-side rendering React app, I have set up a proxy for all HTTP calls to a different port. Take a look at the code snippet below for the HTTP proxy configuration. import proxy from "express-http-proxy"; const app = express(); const bodyParse ...

Pressing the icon will trigger a top-sliding dropdown mobile menu to appear

How can I ensure my mobile dropdown menu slides in from the top when the user clicks the "header-downbar-menu" icon and slides out to the top when clicked again? Currently, the button only shows the menu but I am struggling with writing the JavaScript for ...

Yep, implementing conditional logic with the `when` keyword and radio buttons

I seem to be encountering an issue with my implementation (probably something trivial). I am utilizing React Hook Form along with Yup and attempting to establish a condition based on the selection of a radio group. The scenario is as follows: if the first ...

Adjusting the height of the v-select component in Vuetify 3: A step-by-step guide

Is there a new method to set the height of the "v-select" component in Vuetify version 3? In previous versions, the 'height' prop was used in this way: <v-select :items="..." height="30" /> However, this prop has been ...

Design featuring a combination of vertical columns and a fixed image placed in

I'm currently in the process of creating a website and I have a specific page layout in mind that I would like to implement: ------------------------------------------ | A catchy title | | | Here | An unconve ...

Obtaining HTML data with ajax within a WordPress post

Greetings! I've been putting together a website and I'm eager to include a unique timeline in each of my posts. I'm utilizing WordPress for this project. However, since the timeline I want to insert will vary from post to post, I am unable t ...

How can I make Bootstrap Carousel slides transition as I scroll?

I have implemented the Bootstrap carousel on my website, but I am looking to customize its functionality. Specifically, I would like the slides to change whenever the user scrolls with their mouse. Is there a way to achieve this using Bootstrap Carousel? ...

Ways to create a smooth transition in element height without a known fixed target height

Is it possible to create a smooth height transition for an element when the target height is unknown? Replacing height: unset with height: 100px allows the animation to work, but this presents a problem as the height needs to be based on content and may v ...

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 ...

Using CSS to create a background-clip effect on text along with a smooth opacity

I've coded a unique effect for my <h1> heading text where each letter is enclosed in its own <span> element, like this: <h1 class='gradient-heading' id='fade'> <span>H</span> <span>e</span ...

Characters with accents appear larger compared to regular letters

Currently, I am working on a website that includes special characters like č, ď, ň, ř, š, ž. However, these special letters are appearing larger than the normal letters. For example: https://i.sstatic.net/WBNQg.png I have a .properties file where I ...

Struggling to make Typescript recognize the css prop (emotion) when styling Material-UI components

I'm on a mission to set up a Typescript project with Material-UI v4.11.4 and implement emotion for styling in anticipation of the MUI v5 release. The aim is to integrate emotion into the project so developers can transition to using the new styling in ...

Utilizing the `sx` prop to choose a child component in Material-UI: a step-by

Is there a way to style a specific cell in a table row based on its state, such as activeColNo, using CSS nth-child selector within the sx prop? <TableRow sx={{ "& :nth-child({activeColNo})": { bgcolor: "red" ...