Skip to content
Shane Brinkman-Davis Delamore edited this page May 6, 2017 · 16 revisions

Facebook-React and Art-React

CaffeineScript is ideal for React-style programming.

Facebook React

Writing React code is cleaner in CaffeineScript. Here is a samle example from the Facebook React Examples.

# CaffeineScript
class Timer extends Component
  constructor: ->
    @state = secondsElapsed: 0

  componentDidMount: ->
    @interval = setInterval 
      -> 
        @setState (prevState) -> 
          secondsElapsed: prevState.secondsElapsed + 1      
      1000

  componentWillUnmount: ->
    clearInterval @interval

  render: ->
    Div "" Seconds Elapsed: #{@state.secondsElapsed}

render Timer, mountNode

versus

// JSX
class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {secondsElapsed: 0};
  }

  tick() {
    this.setState((prevState) => ({
      secondsElapsed: prevState.secondsElapsed + 1
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return (
      <div>Seconds Elapsed: {this.state.secondsElapsed}</div>
    );
  }
}

ReactDOM.render(<Timer />, mountNode);

Completing the Example with Style

The Facebook example above isn't complete. It doesn't include any import statements and it doesn't define mountNode. In CaffeineScript, importing the React libraries AND completely replacing JSX takes just three lines of code:

import &react, &reactdom, &ArtStandardLib.createObjectTreeFactories
  [] :div
  React.createElement

I'm not sure how they define mountNode, so we'd need another line or two for that.

Art React

It should come as no surprise that if you are using my ArtSuite with ArtReact, this same component is even leaner.

This is a complete, runnable example. I don't know where the 'mountNode' is defined in the Facebook-react example, so I assume there is more boilerplate code to get to first base.

import &ArtSuite

class Timer extends ArtReact.Component
  @stateFields secondsElapsed: 0

  componentDidMount: ->
    @interval = setInterval 
      -> @secondsElapsed += 1
      1000

  componentWillUnmount: ->
    clearInterval @interval

  render: ->
    CanvasElement
      RectangleElement color: #eee
      TextElement text: "" Seconds Elapsed: #{@secondsElapsed}

initArtSuiteApp MainComponent: Time
Clone this wiki locally