Skip to content
Advertisement

How to get each user’s keystroke when he pressed a certain key?

I need to get each user’s keystroke when he pressed a certain key(“#”) and stop getting his keystroke when he pressed other key(space(” “)). For example: a user enters the text “I wanna go to #shop”, I need to save his input and the tag inside it. How can I do it? I wrote some code to do it but I don’t know how to make it completely

onKeyDown = (e) => {
  let value = e.target.value, tags = [], currentTag = "";

  if (e.key == "Enter") {
    this.setState((state) => {
      const item = this.createNote(value, tags);
      return { notes: [...state.notes, item] };
    });
  }

  if (e.key == "#") {}
};

Advertisement

Answer

You can make use of regex /#[^s]+/g

enter image description here

Live Demo

Codesandbox Demo

export default function App() {
    const [value, setValue] = useState("");
    const [tags, setTags] = useState([]);

    function onInputChange(e) {
        const value = e.target.value;
        setValue(value);

        const tags = value.match(/#[^s]+/g) ?? [];
        setTags(tags);
    }

    return (
        <>
            <input type="text" name="" value={value} onChange={onInputChange} />
            <ul>
                {tags.map((tag) => {
                    return <li key={tag}> {tag} </li>;
                })}
            </ul>
        </>
    );
}

EDITED: You can make use of useMemo hook as

Thanks to 3limin4t0r

Live Demo

Codesandbox Demo

export default function App() {
    const [value, setValue] = useState("");

    const tags = useMemo(() => value.match(/#S+/g) || [], [value]);
    function onInputChange(e) {
        const value = e.target.value;
        setValue(value);
    }

    return (
        <>
            <input type="text" name="" value={value} onChange={onInputChange} />
            <ul>
                {tags.map((tag) => {
                    return <li key={tag}> {tag} </li>;
                })}
            </ul>
        </>
    );
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement