React - Drop down list on typing specific character in input field(example - {{ or @ )

1.9k Views Asked by At

I need to show a list or dropdown when user enters a specific character like '@' or '{{ }}' in the input text area, from which an option can be selected and then used in the text area. Is there any specific library for this in React.js? Or any short solution for this in React?

1

There are 1 best solutions below

0
Summer On

You can monitor the input from the text area and check for the specific character with a regex. Use a state that mounts a component with suggestions when true. Selecting an option would insert it in the text and set the mount state to false. Clicking away should do the same (and MUI includes a click away listener helper component).

Here is a small demo as a proof-of-concept: https://codesandbox.io/s/magical-browser-dk981?file=/src/App.tsx

Note: I've used Recoil to manage the shared state, because I really like it. If you don't want to use Recoil, you have to declare all state in the parent component and pass it down as props to the child.

This demo is obviously not polished, there are no intelligent suggestions as you type, you'll have to implement that yourself. Good luck. :)