pixelkritzel
The blog of developer Timo Zöller

Good looking JSX

A few weeks ago I decided to let Ember.js go. After using it on an on-off base for a year I was just tired of it. And so I’m looking into React.js – the shiny newcomer.

I like the principle that React does one thing – managing the view layer of an application. And the one thing I don’t like is this dangling snippet of “HTML” at the end of an object:

import React, { Component } from 'react';

export class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      foo: 'foo',
      bar: 'bar'
    };
  }

  handleFormSubmit(event) {
    event.preventDefault();
    /* ... */
  }

  render() {
    return (
      <form onSubmit={this.handleFormSubmit.bind(this)}>
        <input type="text" value={this.foo} ref="foo" />
        <button type="submit">Go!</button>
      </form>
    );
  }
}

It looks odd, I don’t want send a web designer down a JS object to change a class or something. And for me it’s still different – it doesn’t contain any real logic. But the render method might do to compute properties. And it kind of messes up my indentation.

But mostly this just represents a very complicated function call …

So I could to this:

import React, { Component } from 'react';

var template = function template() { return(
<form onSubmit={ this.handleFormSubmit.bind(this) } >
  <input type="text" value={ this.foo } ref="foo" />
  <button type="submit">Go!</button>
</form>
)}

export class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
    foo: "foo",
    bar: "bar"
    }
  }

  handleFormSubmit(event) {
    event.preventDefault();
    /* ... */
  }

  render() {
    return(
	  return template.call(this);
    )
  }
}

Much better. But now it is just variable. I could do this:

import React, { Component } from 'react';
import template from './MyComponentsTemplate';

export class MyComponent extends Component {
  /* skipping all this */

  render() {
    retun template.call(this)
  }
}

And creating the file MyComponentsTemplate.js:

import React from 'react';

var template = function() {
  return (
    <form onSubmit={this.handleFormSubmit.bind(this)}>
      <input type="text" value={this.foo} ref="foo" />
      <button type="submit">Go!</button>
    </form>
  );
};

export default template;

Now I have a separate file where people can see or edit the “HTML”. And I feel better knowing that the logic is separated from the presentation.