DEV Community

Cover image for React.js–Get started in Dart #3
Jermaine
Jermaine

Posted on • Originally published at creativebracket.com

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,
          });
        });
      }
});
Enter fullscreen mode Exit fullscreen mode

View the Source

And it's usage:

// web/main.dart
ReactDOM.render(
  React.createElement(
    Ticker,
    null,
    null,
  ),
  querySelector('#output2'));
Enter fullscreen mode Exit fullscreen mode

Watch Part 3 on YouTube
Get the source code


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());
Enter fullscreen mode Exit fullscreen mode

Learn more in this video:

Watch on YouTube
Get the source code


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

Top comments (0)