I'm trying to make an input that has the value keeping in state. When I write something and press ENTER I would like to save the value in state, confirm and send the value (es a default I have console.log). And it works.
But I need to make a second functionality. When I write something and press ESC I would like to discard the changes and go back to previous value. So I mean, if the value is "JAVA" on input, and I write "SCRIPT" and press ESC, still in my state is "JAVA".
This is a piece of code I have now.
import React, { Component } from "react";
import "./styles.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
componentDidMount() {
const value = "Name";
this.setState({ name: value });
}
handleKeyDown = (e) => {
if (e.keyCode === 13) {
this.onSendName();
}
if (e.keyCode === 27) {
//display old value without any changes
}
};
onSendName = () => {
const { name } = this.state;
console.log("Enter", name);
};
handleChange = (e) => {
this.setState({ name: e.target.value });
};
render() {
const { name } = this.state;
return (
<div className="App">
<input
value={name}
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
/>
<div>My state: {name}</div>
</div>
);
}
}
export default App;
And this is sandbox
I think I should add additional value in state and keep my name that till changes and if I press ESC i could display that. I even tried to do it but failed.
Do you, guys, have a similar issue? Or maybe have you seen on SO something similar to that before? I've found a few cases that clear input value, but imo that is useless.
Please about your help.
What I would do is keep the text you want to revert to in state. When you click on the input, set the value of revertValue to this.state.name. When you click esc, set this.state.name to revertValue. Working sample: https://codesandbox.io/s/competent-lumiere-ubq68?file=/src/App.js