m4n5zu
5/30/2017 - 10:03 AM

Hello React - state - how to use state to create dynamic behavior. JsFiddle: http://jsfiddle.net/gh/gist/library/pure/4a834a92e69755964f4f/

Hello React - state - how to use state to create dynamic behavior. JsFiddle: http://jsfiddle.net/gh/gist/library/pure/4a834a92e69755964f4f/

name: ReactJs example by Ryan Vice - www.ViceSoftware.com
description: Hello React - props - how to pass default prop values.
authors:
  - Ryan Vice
resources:
normalize_css: no
wrap: h
panel_js: 3
panel_css: 0
var HelloReact = React.createClass({
  getInitialState: function() {
      return {
          message: 'I am from default state'
      };
  },
  updateMessage: function(e) {
      this.setState({message: e.target.value});
  },
  render: function() {
    return (
      <div>
          <input type='text' onChange={this.updateMessage}/>
    	  <div>Hello React</div>
        <div>{this.state.message}</div>
      </div>
      );
  }
});
 
ReactDOM.render(
  <HelloReact />, 
  document.getElementById('view'));
<script src="https://fb.me/react-with-addons-0.14.0.js"></script>
<script src="https://fb.me/react-dom-0.14.0.js"></script>
 
<div id="view"/>
<div> {this.state.message} </div>
  • anytime this.state.message changes we will see that change reflected in the browser because React will rerender our component.
  • Next we need to wire up our UI to allow us to update this.state.message in response to user input. To do this we will take advantage of the synthetic events capabilities of React's virtual DOM.

Virtual DOM : " React abstracts away the DOM from you, giving a simpler programming model and better performance."

<input type='text' onChange={this.updateMessage}/>

Anytime we change the text in our textbox, this.updateMessage will be called

  updateMessage: function(e) {
      this.setState({message: e.target.value});
  },
  • Components in React are meant to be state machines and changing the state transitions the UI from one visual state to another.