If we have state for the value attribute in the input box, how can we set the previous value when we hit escape in react?

Asked
Active3 hr before
Viewed126 times

11 Answers

previousescapeattributeinputvaluestatereact
90%

We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.,For example, if we want to make the previous example log the name when it is submitted, we can write the form as a controlled component:,Because its value is read-only, it is an uncontrolled component in React. It is discussed together with other uncontrolled components later in the documentation.

<form>
   <label>
      Name:
      <input type="text" name="name" />
   </label>
   <input type="submit" value="Submit" />
</form>
load more v
88%

If you're looking for a document-level key event handling, then binding it during componentDidMount is the best way (as shown by Brad Colthurst's codepen example):,I was thinking of a kind of registering when a component becomes active ,Note that you should make sure to remove the key event listener on unmount to prevent potential errors and memory leaks.

If you're looking for a document-level key event handling, then binding it during componentDidMount is the best way (as shown by Brad Colthurst's codepen example):

class ActionPanel extends React.Component {
  constructor(props){
    super(props);
    this.escFunction = this.escFunction.bind(this);
  }
  escFunction(event){
    if(event.keyCode === 27) {
      //Do whatever when esc is pressed
    }
  }
  componentDidMount(){
    document.addEventListener("keydown", this.escFunction, false);
  }
  componentWillUnmount(){
    document.removeEventListener("keydown", this.escFunction, false);
  }
  render(){
    return (   
      <input/>
    )
  }
}

EDIT: If you are using hooks, you can use this useEffect structure to produce a similar effect:

const ActionPanel = (props) => {
  const escFunction = useCallback((event) => {
    if(event.keyCode === 27) {
      //Do whatever when esc is pressed
    }
  }, []);

  useEffect(() => {
    document.addEventListener("keydown", escFunction, false);

    return () => {
      document.removeEventListener("keydown", escFunction, false);
    };
  }, []);

  return (   
    <input />
  )
};
load more v
72%

So in you handleClick function you need to trigger event like

handleClick() {
   this.setState({
      value: 'another random text'
   })
   var event = new Event('input', {
      bubbles: true
   });
   this.myinput.dispatchEvent(event);
}

Complete code

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    value: 'random text'
    }
  }
  handleChange (e) {
    console.log('handle change called')
  }
  handleClick () {
    this.setState({value: 'another random text'})
    var event = new Event('input', { bubbles: true });
    this.myinput.dispatchEvent(event);
  }
  render () {
    return (
      <div>
        <input readOnly value={this.state.value} onChange={(e) => {this.handleChange(e)}} ref={(input)=> this.myinput = input}/>
        <button onClick={this.handleClick.bind(this)}>Change Input</button>
      </div>
    )
  }
}

ReactDOM.render(<App />,  document.getElementById('app'))

Edit: As Suggested by @Samuel in the comments, a simpler way would be to call handleChange from handleClick if you don't need to the event object in handleChange like

handleClick() {
   this.setState({
      value: 'another random text'
   })
   this.handleChange();
}
load more v
65%

Function will have a this context pointing to an empty object.,If you do not specify return, or this function will return a non-object value, this will get returned from such function.,Every time you see a new followed by a function name, your this will point to a newly created empty object.

var func = function() {
   // ...
};

func()
load more v
75%

It handles the state of inputs with value={formik.values.email} and onChange={formik.handleChange}.,We get a single source of truth for form values in the state.,If you take a closer look, we didn’t have to set up our state, nor handle the onChange or onSubmit events as we’d typically do with React.

The markup for a straightforward HTML form might look something like this:

<form>
     <div className="formRow">
          <label htmlFor="email">Email address</label>
          <input type="email" name="email" className="email" />
        </div>
     <div className="formRow">
          <label htmlFor="password">Password</label>
          <input type="password" name="password" className="password" />
        </div>
     <button type="submit">Submit</button>
</form>
load more v
40%

If you'd rather not have the dialog always rendered, you can put a guard in front of it and only render when it should be open. In this case you don’t need the isOpen prop at all.,An accessible dialog or "modal" window.,High-level component to render a modal dialog window over the top of the page (or another dialog).

function Example(props) {  const [showDialog, setShowDialog] = React.useState(false);  const open = () => setShowDialog(true);  const close = () => setShowDialog(false);
  return (    <div>      <button onClick={open}>Open Dialog</button>
      <Dialog isOpen={showDialog} onDismiss={close}>        <button className="close-button" onClick={close}>          <VisuallyHidden>Close</VisuallyHidden>          <span aria-hidden>×</span>        </button>        <p>Hello there. I am a dialog</p>      </Dialog>    </div>  );}
load more v
22%

If you forget to add var you will be assigning a value to an undeclared variable, and the results might vary.,If you only have a getter, the property cannot be set, and any attempt at doing so will be ignored:,If you only have a setter, you can change the value but not access it from the outside:

The simplest one is to add the React JavaScript file into the page directly. This is best when your React app will interact with the elements present on a single page, and not actually controls the whole navigation aspect.

/n

In this case, you add 2 script tags to the end of the body tag:

body
load more v
60%

The value argument sets the value attribute.,When an input element’s type attribute is in the Reset Button state, the rules in this section apply.,Let value be the value attribute’s number.

[OverrideBuiltins]
interface HTMLFormElement: HTMLElement {
   attribute DOMString acceptCharset;
   attribute DOMString action;
   attribute DOMString autocomplete;
   attribute DOMString enctype;
   attribute DOMString encoding;
   attribute DOMString method;
   attribute DOMString name;
   attribute boolean noValidate;
   attribute DOMString target;

   [SameObject] readonly attribute HTMLFormControlsCollection elements;
   readonly attribute unsigned long length;
   getter Element(unsigned long index);
   getter(RadioNodeList or Element)(DOMString name);

   void submit();
   void reset();
   boolean checkValidity();
   boolean reportValidity();
};
load more v
48%

Unfortunately, I don't have the time to maintain this project anymore. If you are interested to help, please reach out to me on Twitter @moroshko.,For example, to display suggestions only when input value is at least 3 characters long, do:,When rendering multiple sections, you need to tell Autosuggest how to render a section title.

yarn add react - autosuggest
load more v
23%

To use, set the accessibilityLabel property to a custom string on your View, Text or Touchable:,To use, set the accessibilityHint property to a custom string on your View, Text or Touchable:,In the above example, we can't get accessibility focus separately on 'text one' and 'text two'. Instead we get focus on a parent view with 'accessible' property.

<View accessible={true}>  <Text>text one</Text>  <Text>text two</Text></View>
load more v
90%

 Pretag team - issue, fix, solve, resolve

Other "previous-escape" queries related to "If we have state for the value attribute in the input box, how can we set the previous value when we hit escape in react?"