-
Notifications
You must be signed in to change notification settings - Fork 6
React
CaffeineScript is ideal for React-style programming.
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);
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.
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
- Home
- Get Started
- Benefits
- Highlights
- Productivity by Design
- CaffeineScript Design
- What is CaffeineScript Good For?
- Get the most out of JavaScript
- Language Comparison
- CHANGELOG
- Blocks Instead of Brackets
- Binary Line-Starts
- Everything Returns a Value
- Streamlined Modules
- Scopes and Variables
- Optional Commas
- Semantics
- Ambiguities