Thursday, July 21, 2016

Reflections on Learning React....

What's quiet amusing (and frustrating….) is that the simplest user interactions with page elements have to be relearnt in a way fitting the paradigms of the React model. As an example, imagine a search form. Just a text box and a button, simple right? In "classic" JS, adding an onclick event handler to read and search on the value in the textbox takes no thought at all (ignoring here the "production -quality" trimmings that are necessary in a real world form, such as validation).

Reproducing this interaction in React requires knowledge of a few principles:
  • Event handlers are attached to an element as a property. If using JSX, be careful not to enclose the handler in quotes!
     < input onclick={this.submitSearch} type="button" value="Search" />
    
  • The "this" context pointing to the React component is not available in the event handler. That means that if the value in the text box is bound to a member of the component state, this value would not be accessible in the handler. There are two approaches to correcting this - either add the "bind(this)" call to the end of the handler invocation
     < input onclick={this.submitSearch.bind(this)} type="button" value="Search" /> 
    or define the handler as an arrow function
    submitSearch = ( e ) => { … }
  • Bind the text box default value to an initial value. Do not bind the value property, as doing so causes the box to behave as read only in the form. Also need to add an onchange handler for the text box, bound to a function that updates the appropriate member of the state object with the value from the control (e.target.value)
  • Add the shouldComponentUpdate() lifecycle function to the component, ensuring that the change of text value in the state member does not trigger the update (unless you want the search to occur on every key stroke)
  • Setting the state in React (using Typescript in VS Code) requires all members of the state object to be set each time

No comments: