N
N
Nikolai2019-06-07 15:37:01
JavaScript
Nikolai, 2019-06-07 15:37:01

How to make popup hints as you type?

Hello.
The main question:
1. How to make it so that when entering information in a field (TextField from MaterialUI), a window appears below the field with hints that are loaded from the server. At the same time, so that the data from this field - TextField is also sent to the server and submitting the form.
Additional question:
2. How, when clicking on one of the hints, fill the form with data that comes from the server

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2019-06-07
@wiigusev

1. Hang a listener on onChange, which will make the appropriate request to the server. Upon arrival, the data must be drawn. It's better to use debounce and check for minimum string length before requesting.
2. Attach an onClick listener to the hint and change the value of the required input in the handler.
A simple example of implementing such logic:

import React, { useState, useRef, useCallback, useMemo } from 'react';
import debounce from 'lodash/debounce';
import { fetchSomeData } from './someplace';

const Example = () => {
  const [results, setResults] = useState([]);
  const inputEl = useRef(null);

  const handleTintClick = useCallback((value) => {
    inputEl.current.value = value;
  }, [inputEl]);

  const handleInputChange = useMemo(() => debounce(e => {
    const { value } = e.target;

    if (value.length < 3) return;

    fetchSomeData(value).then(setResults);
  }, 800), []);

  return (
    <>
      <input ref={inputEl} onChange={handleInputChange} />
      {results.length > 0 && (
        <ul>
          {results.map((result, i) => (
            <li
              onClick={() => hanldeTintClick(result.title}}
              key={result.id}
            >
              {result.title}
            </li>
          )}
        </ul>
      )}
    </>
  );
};

debounce is needed to optimize the number of requests to the server. The callback will only be called when the user pauses input for 800ms, if this is a lot, then the timeout can be made less.
useMemo instead of useCallback to avoid debounce every redraw.
It is clear that in real code, instead of ul / li, there should be a styled component. The MateralUI documentation has examples of using their components.

D
davidnum95, 2019-06-07
@davidnum95

https://material-ui.com/components/popover/
When input is focused, change open to true. Inside Popover we load and interact as we want.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question