I have been working on the React and Redux series of projects. I recently passed the “Manage State Locally” exercise; however, I would like to enhance the functionality of the code I have so far by adding an event handler that will detect an enter key press and trigger the click event on the “Add message” button.
However, based on my Internet searches, it doesn’t appear adding IDs to React components is a good idea. This makes sense to me because the whole goal of React is to have reusable components, and if an ID is hard-coded into a JSX element, within a React component, then that functionality breaks if the component is reused.
Is there a good strategy for this with React components? I assume it’s more complicated than the vanilla JS solution, above
Hey @Audiosyncrasy, this is a great question! I can propose a solution that does that same kind of event listening, but follows the React design concept.
What you’re trying to do is listen for the “Enter” button, which will not be triggered by onChange. You can add onKeyPress in order to listen for other keystrokes. The input would become:
Just to update this topic for people currently looking for this info: the keypress event has been deprecated in favour of keydown (keydown documentation) and the corresponding React prop is onKeyDown.