In Part 2 we continued looking at the React documentation examples while implementing them in Dart. We began by refactoring the createReactClass
function to use named parameters in an attempt to simplify the writing of components:
// web/components/ticker.dart
...
...
var Ticker = createReactClass(
getInitialState: () => makeJsObject({
"seconds": 0,
}),
componentDidMount: (ReactClassInterface self) {
self.interval = Timer.periodic(Duration(seconds: 1), (_) => self.tick());
},
componentWillUnmount: (ReactClassInterface self) {
self.interval.cancel();
},
render: (ReactClassInterface self) => React.createElement(
'div',
null,
['Seconds ${getProperty(self.state, "seconds")}'],
),
methodMap: {
"tick": (ReactClassInterface self) {
self.setState((dynamic state) {
var seconds = getProperty(state, "seconds") as int;
return makeJsObject({
"seconds": seconds + 1,
});
});
}
});
And it’s usage:
// web/main.dart
ReactDOM.render(
React.createElement(
Ticker,
null,
null,
),
querySelector('#output2'),
);
In this final part we will be using the react package to build out the other examples. The react package provides a much friendlier API for building custom components:
import 'dart:async';
import 'package:react/react.dart';
class TickerComponent extends Component {
Timer interval;
tick() { ... }
@override
Map getInitialState() => {'seconds': 0};
@override
componentDidMount() { ... }
@override
componentWillUnmount() { ... }
@override
render() => div({}, 'Seconds ${state["seconds"]}');
}
var Ticker = registerComponent(() => TickerComponent());