React
The React filter enables you to build React components.
When a class definition is encountered that derives from React::Controller
,
the following transformations are applied:
-
An
import
statement for React will be generated -
intialize
methods will constructthis.state
-
Instance variables (
@var
) accesses will be mapped tothis.state
. Instance variable updates will be mapped tothis.setState
.- Except within
componentWillReceiveProps
methods, where accesses are mapped to the first argument passed.
- Except within
-
Class variables (
@@var
) will be mapped tothis.props
. Updates to class variables is not supported. - Three different HTML rendering syntaxes are supported:
React.createElement
calls.- A JSX-like syntax, wrapped in
%x{...}
. This differs from JSX primarily in that expressions are in Ruby syntax. - Wunderbar syntax.
-
When using either JSX-like or Wunderbar syntaxes, sequences of elements will automatically be wrapped in React Fragments when they occur in places where a single element is required.
-
onChange
functions are automatically generated for controlled components. - ReactDOM calls are also supported, and generate a separate
import
statement.
For more information, see the examples provided.
Hooks
React hooks are an alternate
mechanism for expressing React components. Components expressed as hooks tend
to be smaller than the equivalent code expressed as JavaScript classes.
Perhaps the most important difference is that at this time,
React refresh will only update
hooks in a running application without losing state. The most notable
limitation of hooks is that you can’t use the ref
attribute on
hooks.
To enable hooks, change your component from inheriting from React::Component
to React
. If this is done, a React hook will be generated if all of the
following conditions are met:
- No class/static methods (
def self.
) - No use of
React lifecycle methods
other than
render
. - No attribute accessors (getters/setters)
If any of these conditions are not met, a class inheriting from
React.component
will be emitted instead. This means that you can code both
classes and hooks using the same syntax.