Creative Bracket

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

Conclusion

I hope this was insightful and you learned something new today.

Subscribe to my YouTube channel to be notified on future React videos. Thanks!

Like, share and follow me 😍 for more content on Dart.

Further reading

  1. react package
  2. How to Use JavaScript libraries in your Dart applications
  3. Full-stack web development with Dart

Jermaine Oppong

Hello 👋, I show programmers how to build full-stack web applications with the Dart SDK. I am passionate about teaching others, having received tremendous support on sites like dev.to and medium.com for my articles covering various aspects of the Dart language and ecosystem.

Useful learning materials