1

In AngularJS I can do:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="firstname">
    <h1>{{firstname}}</h1>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";    
});
</script>

</body>
</html>

What is the equivalent way to do this in React? Here is what I have tried:

var app = document.getElementById("app");



var Main = React.createClass({
  getInitialState: function(){
    return {text: ""};
  },
  change: function(e){
    var newValue = e.target.value;
    this.setState({text: newValue});
  },
  render: function(){
    return (
      <div>
        <input onChange={this.change} type="text"/>
        <h1>{this.state.text}</h1>
      </div>
      );
  }
});


React.render(<Main />, app);

Is it the best way for implementing this?
This way seems to be a little slow. Can you suggest another way?

member555
  • 797
  • 1
  • 13
  • 40
  • 1
    Yes, this seems like a reasonable way to do it. What do you mean this "seems" slow? – aziz punjani Aug 31 '16 at 12:06
  • @azizpunjani It seems to my eye that updating the view on each change is slow. I understand that angular do the same, but maybe they have a better way instead of using onChange attribute – member555 Aug 31 '16 at 12:18
  • 1
    Thinking in React requires us to discontinue thought about two-way bindings, and start thinking about unidirectional data flow. Data flows up, events flow up. Also, read up on Reacts VDOM if you're concerned about rendering performance. – lux Aug 31 '16 at 16:12
  • 1
    @lux data flows *down* :-) – aziz punjani Oct 17 '16 at 14:21
  • @azizpunjani Yeah, clearly a typo -_- Good catch – lux Oct 17 '16 at 14:43
  • I came to SO to ask the same question. In the react quick start docs there's a form example: `handleChange(event) { this.setState({value: event.target.value}); }` ... `` Having in mind the concept of two way binding from angular... this way, of wiring events for every input to update the state... seems overkill! Is this really the react way of doing things? – Stefan Balan May 23 '17 at 21:11

0 Answers0