Skip to main content

React.js - Get started in Dart #3

Published 1 min readMarkdown
React.js - Get started in Dart #3

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());

Further reading

  1. react package

  2. How to Use JavaScript libraries in your Dart applications

  3. Full-stack web development with Dart

About the author

  • I'm Jermaine, a Web Developer, Technical Writer and Programming Instructor. Having worked with various languages in the IT industry for over 13+ years now, I am here to share my knowledge on software development with the community.

No comments yet. Be the first to comment.

More from this blog