I have a React app with the following structure:
<App>
<Input/>
<Lists>
<List>
.
.
<List/>
</Lists>
</App>
Each list has modify button which makes the list display an input field if clicked and some text otherwise by toggling modify(a boolean state).
What I want to achieve is that on clicking the escape key user should be able to switch between both (the input field and the text).
What I've tried:
Use
document.addEventListener
, but I could not access the event handler (which is in the List class), I couldn't add it inside the class itself as it assumesList.document
to be a property.Use the
onKeyPress
synthetic event
I couldn't figure out how to add it to the app ponent (I want the user to click escape anytime, not focus on the input field or something and then press escape)
I added it to the Input field (the one replaced by the text in List) but it didn't work (It works with the enter key, I used event.key==='Escape'
). I console logged the event and nothing es up while it works fine for the Enter key.
All suggestions appreciated :).
I have a React app with the following structure:
<App>
<Input/>
<Lists>
<List>
.
.
<List/>
</Lists>
</App>
Each list has modify button which makes the list display an input field if clicked and some text otherwise by toggling modify(a boolean state).
What I want to achieve is that on clicking the escape key user should be able to switch between both (the input field and the text).
What I've tried:
Use
document.addEventListener
, but I could not access the event handler (which is in the List class), I couldn't add it inside the class itself as it assumesList.document
to be a property.Use the
onKeyPress
synthetic event
I couldn't figure out how to add it to the app ponent (I want the user to click escape anytime, not focus on the input field or something and then press escape)
I added it to the Input field (the one replaced by the text in List) but it didn't work (It works with the enter key, I used event.key==='Escape'
). I console logged the event and nothing es up while it works fine for the Enter key.
All suggestions appreciated :).
Share Improve this question edited Mar 14, 2021 at 17:00 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 16, 2017 at 19:07 Ayush RawalAyush Rawal 1132 silver badges8 bronze badges 2- Also, you can see the effect I want by clicking on the search input field on this question page and pressing escape – Ayush Rawal Commented Dec 16, 2017 at 19:09
- 1 Possible duplicate of How to detect Esc Key Press in React and how to handle it – Chase Sandmann Commented May 11, 2018 at 15:44
1 Answer
Reset to default 7The escape key does not fire keypress
event. You're going to want to listen for the keydown
event.
class App extends PureComponent {
// ...
ponentDidMount() {
window.addEventListener('keydown', callback);
}
ponentWillUnmount() {
window.removeEventListener('keydown', callback);
}
// ...
}