Tuesday, September 6, 2016

react 101

For grins I fired up React, went through its nice tutorial.

I'm trying to think about what I feel about it. It feels nice and clean relative to some other things, and I dig that it's a library and not a framework; it does what it does very well. On the other hand, I'm not always convinced what it does is worth doing, namely, it seems like a lot of engineers really hate working directly on the DOM. But, I think I haven't dug far enough to get into React's sweet spot, and many people like it a lot better when they combine it with its Flux implementation "Redux".

Anyway, I decided to practice what I had studied with a simple helper toy (I'm rearranging the physical folder layout for the domains I host on my server, a lot of fiddly bits to keep track of)... to get there I decided to recreate the classic Angular "hey you synch up a text input and its display with no code!!!".   Here's a fiddle I spun off their Hello World that does that.

var Angularish = React.createClass({
getInitialState: function(){
    return { site:'foo' };
  },
  updateSite: function(e){
  this.setState({ site : e.target.value});
  },
  render: function() {
    return <div><input value={this.state.site} onChange={this.updateSite} /> {this.state.site}</div>;
  }
});

ReactDOM.render(
  <Angularish />,
  document.getElementById('container')
);

I dig that React is very event based; I think a lot of other toolkits rely too much on shared memory and watches and you never know when anything is happening. On the other hand, like all these toolkits it's so very finicky with the syntaxes it introduces; the JSX bit (the little html/XML tag like thing) had to be a properly closed tag (even singletons, in the xhtml sense), a tag value has to be either a string or an {expression} and not a mix, etc, and I had to learn you can't just modify this.state directly.

(for my personal future reference here's the https://jsfiddle.net/sfh7ydpw/1/ I made with more detailed steps for the refactoring; I guess revealing the old and new folder structure isn't much of a security risk.)

2018 UPDATE

Guess it's too much to hope that 1 1/2 year old code would still work.
Here's the updated fiddle: https://jsfiddle.net/69z2wepo/171740/
class Angularish extends React.Component {
constructor(props){
  super(props);
    this.updateSite = this.updateSite.bind(this);
    this.state =  { site:'foo' };
  };
  updateSite(e){
  this.setState({ site : e.target.value});
  };
  render() {
    return <div><input value={this.state.site} onChange={this.updateSite} /> {this.state.site}</div>;
  }
};

ReactDOM.render(
  <Angularish />,
  document.getElementById('container')
);
That's closer to the example presented in https://reactjs.org/docs/lifting-state-up.html
That seems like a surprisingly large amount of shitty boilerplate, tho... this.updateSite = this.updateSite.bind(this); is sort of uncool.

No comments:

Post a Comment