A Stateful Component
A Stateful Component
This example focuses on managing state, and making use of React component lifecycle methods.
While it is possible to use this.state to reference state and
this.setState to update state within React components expressed in Ruby
syntax, the more natural way to express state in Ruby classes is with
instance variables (for example, @seconds).
class Timer < React
def initialize
@seconds = 0
end
def tick()
@seconds += 1
end
def componentDidMount()
self.interval = setInterval(tick, 1_000)
end
def componentWillUnmount()
clearInterval(self.interval)
end
def render
React.createElement 'div', nil, 'Seconds: ', @seconds
end
end
ReactDOM.render(
React.createElement(Timer, nil),
document.getElementById('timer-example')
)
Results
Commentary
Statement by statement:
-
For convenience, this filter will convert classes that inherit simply from
Reactas well asReact::Componentto React components. -
JavaScript
constructorbecomes Ruby’sinitialize. Defining apropsargument and callingsuperis optional, and will be done for you automatically if necessary (in this example,propsis not needed). Defining initial values is done by instance variable assignment rather than explicitly creating athis.stateobject. -
The
tickmethod updates state via an assignment statement rather than by calling thesetStatemethod. - The
componentDidMountlifecycle method will cause thetickmethod to be called every 1,000 milliseconds. Notes:- The
tickmethod can be passed directly without the need for an anonymous function. self.instanceis a property on the instance that is not a part of React’s state for the object.
- The
-
The
componentWillUnmountlifecycle method will cancel the timer. -
The
rendermethod outputs the number of seconds within an HTMLdivelement. With React.js, the use of JSX is optional and you can directly code calls toReact.createElement, and this works in Ruby2JS too. - The
ReactDOM.rendermethod also accepts calls toReact.createElement.