Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://workiva.github.io/over_react/
A library for building statically-typed React UI components using Dart.
https://workiva.github.io/over_react/
Last synced: 10 days ago
JSON representation
A library for building statically-typed React UI components using Dart.
- Host: GitHub
- URL: https://workiva.github.io/over_react/
- Owner: Workiva
- License: other
- Created: 2016-10-11T22:56:57.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2024-05-22T11:33:21.000Z (6 months ago)
- Last Synced: 2024-05-22T11:54:17.269Z (6 months ago)
- Language: Dart
- Homepage:
- Size: 37.5 MB
- Stars: 422
- Watchers: 40
- Forks: 58
- Open Issues: 53
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
- awesome-dart - OverReact - A library for building statically-typed React UI components. (Client Web App Frameworks)
README
# OverReact
A library for building statically-typed React UI components using Dart.
This library also exposes _OverReact Redux_, which has [its own documentation](doc/over_react_redux_documentation.md).
[![Pub](https://img.shields.io/pub/v/over_react.svg)](https://pub.dev/packages/over_react)
[![Documentation](https://img.shields.io/badge/docs-over_react-blue.svg)](https://pub.dev/documentation/over_react/latest/)
[![OverReact Analyzer Plugin (beta)](https://img.shields.io/badge/docs-analyzer_plugin_(beta)-ff69b4.svg)](https://workiva.github.io/over_react/analyzer_plugin/)
[![Join the gitter chat](https://badges.gitter.im/over_react/Lobby.svg)][gitter-chat][![Dart CI](https://github.com/Workiva/over_react/workflows/Dart%20CI/badge.svg?branch=master)](https://github.com/Workiva/over_react/actions?query=workflow%3A%22Dart+CI%22+branch%3Amaster)
---
* __[Migration Guides](#migration-guides)__
* __[Using OverReact](#using-overreact)__
* [Running tests in your project](#running-unit-tests-in-your-project)
* [OverReact Component Unit Test Examples](#overreact-component-unit-test-examples)
* __[Anatomy of an OverReact component](#anatomy-of-an-overreact-component)__
* [UiFactory](#uifactory)
* [UiProps](#uiprops)
* [UiState](#uistate)
* [UiComponent2](#uicomponent2)
* __[Fluent-style component consumption](#fluent-style-component-consumption)__
* __[DOM components and props](#dom-components-and-props)__
* __[Component Formatting](#component-formatting)__
* __[Building custom components](#building-custom-components)__
* __[Component Boilerplates](#component-boilerplate-templates)__
* __[Component Best Practices](#component-best-practices)__
* __[Contributing](#contributing)__[](#__START_EMBEDDED_README__)
## Migration Guides
### Null safety
over_react 5.0.0 introduces support for null safety.Now, you can declare non-nullable required props, using the `late` keyword. See [the docs null safety and required props](./doc/null_safety_and_required_props.md) for more information.
To migrate components to null safety, see our [__null safety migration guide__](doc/null_safety/null_safe_migration.md).
### More Migration Guides
- [__New component boilerplate__](doc/new_boilerplate_migration.md): How to update to the mixin-based (`mixin MyProps on UiProps {}`) over_react component declaration syntax.
- [__UiComponent2__](doc/ui_component2_transition.md): How to move off the deprecated `UiComponent` base class and onto `UiComponent2`.
- [__BuiltRedux to Redux__](doc/built_redux_to_redux.md): How to transition to OverReact Redux from BuiltRedux.
- [__Flux to Redux__](doc/flux_to_redux.md): A guide to how to transition from w_flux to OverReact Redux. This guide also introduces a new architecture, Influx, that can be used for incremental refactors.
- [__Dart2 Migration__](doc/dart2_migration.md): Documentation on the Dart 2 builder updates and how to transition componentry to Dart 2.
## Using OverReact
> __Prerequisites__
>
> - __Familiarize yourself with React JS__
>
> Since OverReact is built atop React JS, we strongly encourage you to gain familiarity with it by reading some [React JS tutorials][react-js-tutorial] first.
>
> - __Familiarize yourself with Dart Web applications__
>
> If you have never built a Web application in Dart, we strongly encourage you to gain familiarity with the core terminology, tools and boilerplate necessary to serve an application locally using Dart. [Dart has fantastic documentation and tutorials to get you started](https://dart.dev/tutorials/web/get-started).1. Add the `over_react` package as a dependency in your `pubspec.yaml`.
```yaml
dependencies:
over_react: ^4.0.0
```
1. Enable the **[OverReact Analyzer Plugin (beta)](tools/analyzer_plugin/)**, which has many lints and assists to make authoring OverReact components easier!1. Include the native JavaScript `react` and `react_dom` libraries in your app’s `index.html` file,
and add an HTML element with a unique identifier where you’ll mount your OverReact UI component(s).```html
// OverReact component render() output will show up here.
```> __Note:__ When serving your application in production, use `packages/react/react_with_react_dom_prod.js`
file instead of the un-minified `react.js` / `react_dom.js` files shown in the example above.1. Import the `over_react` and `react_dom` libraries into `index.dart`. Then [build some components](#building-custom-components) and mount / render a React tree within the HTML element you created in the previous step by calling `react_dom.render()` within the `main()` entrypoint of your Dart application.
> Be sure to namespace the `react_dom.dart` import as `react_dom` to avoid collisions with `UiComponent.render`
when [creating custom components](#building-custom-components).```dart
import 'dart:html';
import 'package:over_react/react_dom.dart' as react_dom;
import 'package:over_react/over_react.dart';// Example of where the `Foo` component might be exported from
import 'package:your_package_name/foo.dart';main() {
// Mount / render your component/application.
react_dom.render(
Foo()(),
querySelector('#react_mount_point'),
);
}
```1. Run `webdev serve` in the root of your Dart project.
> **Note:** If you're not using [the latest component boilerplate](doc/new_boilerplate_migration.md), you'll have to restart your analysis server in your IDE for the built types to resolve properly after the build completes. Unfortunately, this is a [known limitation in the analysis server at this time](https://github.com/dart-lang/sdk/issues/34344).
>
> [__Migrate your components to the latest component boilerplate to never worry about this again!__](doc/new_boilerplate_migration.md)
### Running unit tests in your project
When running unit tests on code that uses the over_react [builder] _(or any code that imports `over_react`)_,
__you must run your tests using the `build_runner` package__.> **Warning:** Do **_not_** run tests via `pub run build_runner test` in a package while another instance of `build_runner`
(e.g. `pub run build_runner serve`) is running in that same package. [This workflow is unsupported by build_runner](https://github.com/dart-lang/build/issues/352#issuecomment-461554316)1. Run tests using the `build_runner` package, and specify the platform to be a browser platform. Example:
```bash
$ pub run build_runner test -- -p chrome test/your_test_file.dart
```#### OverReact Component Unit Test Examples
Below are links to a UI component from our example ["Todo App"](https://github.com/Workiva/over_react/tree/master/app/over_react_redux/todo_client), and its analogous tests that we've written for components we use in . We utilize the utilities found in our [`over_react_test` library](https://github.com/Workiva/over_react_test).
* __`TodoListItem`__
* [Component Definition](app/over_react_redux/todo_client/lib/src/components/todo_list_item.dart)
* [Component Unit Tests](app/over_react_redux/todo_client/test/unit/browser/components/todo_list_item_test.dart)
* ["Connected" OverReact Redux Unit Tests](app/over_react_redux/todo_client/test/unit/browser/components/connected_todo_list_item_test.dart)
## Anatomy of an OverReact component
> __If you are not familiar with React JS__
>
> Since OverReact is built atop React JS, we strongly encourage you to gain
> familiarity with it by reading this [React JS tutorial][react-js-tutorial] first.The `over_react` library functions as an additional "layer" atop the [Dart react package][react-dart]
which handles the underlying JS interop that wraps around [React JS][react-js].The library strives to maintain a 1:1 relationship with the React JS component class and API.
To do that, an OverReact component is comprised of four core pieces that are each wired up
via our [builder].1. [UiFactory](#uifactory)
2. [UiProps](#uiprops)
3. component, either a:
1. function component [uiFunction](#uifunction-function-components)
2. class component [UiComponent2](#uicomponent2-class-based-components) (and optionally a [UiState](#uistate))
### UiFactory
__`UiFactory` is a function__ that returns a new instance of a component's [`UiProps`](#uiprops) class.
```dart
// Class component
UiFactory Foo = castUiFactory(_$Foo);// Function component
UiFactory Foo = uiFunction((props) { /*...*/ }, _$FooConfig);
```* This factory is __the entry-point__ to consuming any OverReact component.
* The `UiProps` instance it returns can be used [as a component builder](#uiprops-as-a-builder),
or [as a typed view into an existing props map](#uiprops-as-a-map).
* `castUiFactory` is necessary to prevent implicit cast analysis warnings before code generation has been run.
### UiProps
__`UiProps` is a `Map` class__ that adds statically-typed getters and setters for each React component prop.
It can also be invoked as a function, serving [as a builder](#uiprops-as-a-builder) for its analogous component.```dart
mixin FooProps on UiProps {
// ... the props for your component go here
String? bar;
bool? baz;
List? bizzles;
}
```
* * **Note:** The [builder] generates a class with getters and setters overriding the fields you declare in your mixin, but you don't need to worry about that generated class. To use props from another mixin, simply mix it in! See [_"With other mixins"_](#with-other-mixins) below for more information.
#### With other mixins
__To compose props mixin classes__, create a class alias that uses `UiProps` as the base and mix in multiple props mixins. The generated props implementation will then use it as the base class and implement the generated version of those props mixins.
```dart
UiFactory Foo = castUiFactory(_$Foo); // ignore: undefined_identifiermixin FooPropsMixin on UiProps {
String? bar;
bool? baz;
List? bizzles;
}class FooProps = UiProps with FooPropsMixin, BarPropsMixin;
class FooComponent extends UiComponent2 {
// ...
}
```##### Composition
The use-case for composing multiple props mixins into a single component props class is typically a component that renders another component, and therefore needs to expose the prop interface of that child component which will get forwarded via [`addUnconsumedProps`](https://pub.dev/documentation/over_react/3.1.0/over_react/UiComponent2/addUnconsumedProps.html).[__Check out an example of props mixin component composition here__](doc/props_mixin_component_composition.md)
#### UiProps as a Map
> [!WARNING]
> Directly reading `late` required props on arbitrary maps is unsafe.
>
> See the docs on [Unsafe Required Prop Reads](doc/null_safety_and_required_props.md#unsafe-required-prop-reads)
> for more information and for instructions on how to read these props safely.```dart
UiFactory Foo = castUiFactory(_$Foo); // ignore: undefined_identifiermixin FooProps on UiProps {
String? color;
}class FooComponent extends UiComponent2 {
// ...
}void bar() {
FooProps props = Foo();props.color = '#66cc00';
print(props.color); // #66cc00
print(props); // {FooProps.color: #66cc00}
}/// You can also use the factory to create a UiProps instance
/// backed by an existing Map.
void baz() {
Map existingMap = {'FooProps.color': '#0094ff'};FooProps props = Foo(existingMap);
print(props.color); // #0094ff
}
```
#### UiProps as a builder
```dart
UiFactory Foo = castUiFactory(_$Foo); // ignore: undefined_identifiermixin FooProps on UiProps {
String? color;
}class FooComponent extends UiComponent2 {
ReactElement bar() {
// Create a UiProps instance to serve as a builder
FooProps builder = Foo();// Set some prop values
builder
..id = 'the_best_foo'
..color = '#ee2724';// Invoke as a function with the desired children
// to return a new instance of the component.
return builder('child1', 'child2');
}/// Even better... do it inline! (a.k.a fluent)
ReactElement baz() {
return (Foo()
..id = 'the_best_foo'
..color = 'red'
)(
'child1',
'child2'
);
}
}
```> See [_fluent-style component consumption_](#fluent-style-component-consumption) for more examples on builder usage.
### UiState
__`UiState` is a `Map` class__ _(just like `UiProps`)_ that adds statically-typed getters and setters
for each React component state property in a class component.```dart
mixin FooState on UiState {
// ...
}
```> `UiState` is optional, and won’t be used for every component. Check out the [`UiStatefulComponent` boilerplate](#stateful-component-boilerplate) for more information.
* **Note:** The [builder] will make the concrete getters and setters available from the mixin fields you author in a generated class. To mix state classes together, the mixin class should be used rather than the generated props class. See [_"With other mixins"_](#with-other-mixins) above for more information.
### UiComponent2 (class-based components)
> For guidance on updating to `UiComponent2` from `UiComponent`, check out the [UiComponent2 Migration Guide](doc/ui_component2_transition.md).__`UiComponent2` is a subclass of [`react.Component2`][react.Component2]__, containing lifecycle methods and rendering logic for components.
```dart
class FooComponent extends UiComponent2 {
// ...
}
```* This class provides statically-typed props via [`UiProps`](#uiprops), as well as utilities for prop forwarding and CSS class merging.
* The `UiStatefulComponent2` flavor augments `UiComponent2` behavior with statically-typed state via [`UiState`](#uistate).
### uiFunction (function components)
__`uiFunction` lets you declare a function component__.In JavaScript, function components are just plain functions, but in over_react this wrapper is needed to perform JS interop and wire up the typed props class.
```dart
mixin FooProps on UiProps {
bool? isDisabled;
List? items;
}UiFactory Foo = uiFunction((props) {
// Set default props using null-aware operators.
final isDisabled = props.isDisabled ?? false;
final items = props.items ?? [];// Return the rendered component contents here.
return Fragment()(
Dom.div()(items),
(Dom.button()..disabled = isDisabled)('Click me!'),
);
}, _$FooConfig); // The generated props config will match the factory name.usageExample() => (Foo()..items = ['bar'])();
```
#### Accessing and manipulating props / state within UiComponent2
* Within the `UiComponent2` class, `props` and `state` are not just `Map`s.
They are instances of `UiProps` and `UiState`, __which means you don’t need String keys to access them!__
* `newProps()` and `newState()` are also exposed to conveniently create empty instances of `UiProps` and `UiState` as needed.
* `typedPropsFactory()` and `typedStateFactory()` are also exposed to conveniently create typed `props` / `state` objects out of any provided backing map.```dart
UiFactory Foo = castUiFactory(_$Foo); // ignore: undefined_identifiermixin FooProps on UiProps {
late String color;
Function()? onDidActivate;
Function()? onDidDeactivate;
}
mixin FooState on UiState {
late bool isActive;
}class FooComponent extends UiStatefulComponent2 {
@override
Map get defaultProps => (newProps()
..color = '#66cc00'
);@override
Map get initialState => (newState()
..isActive = false
);@override
void componentDidUpdate(Map prevProps, Map prevState, [dynamic snapshot]) {
var tPrevState = typedStateFactory(prevState);
var tPrevProps = typedPropsFactory(prevProps);if (state.isActive && !tPrevState.isActive) {
props.onDidActivate?.call();
} else if (!state.isActive && tPrevState.isActive) {
props.onDidDeactivate?.call();
}
}@override
dynamic render() {
return (Dom.div()
..modifyProps(addUnconsumedDomProps)
..style = {
...newStyleFromProps(props),
'color': props.color,
'fontWeight': state.isActive ? 'bold' : 'normal',
}
)(
(Dom.button()..onClick = _handleButtonClick)('Toggle'),
props.children,
);
}void _handleButtonClick(SyntheticMouseEvent event) {
setState(newState()
..isActive = !state.isActive
);
}
}
```
## Fluent-style component consumption
> The **[OverReact analyzer plugin](tools/analyzer_plugin/)** has many lints and assists to make authoring OverReact components easier!
In OverReact, components are consumed by invoking a `UiFactory` to return a new `UiProps` builder, which is then modified and invoked to build a [`ReactElement`][ReactElement].
This is done to make "fluent-style" component consumption possible, so that the OverReact consumer experience is very similar to the [React JS][react-js] / "vanilla" [react-dart]
experience.To demonstrate the similarities, the example below shows a render method for JS, JSX, react-dart, and over_react that will have the exact same HTML markup result.
* __React JS__:
```es6
render() {
return React.createElement('div', {className: 'container'},
React.createElement('h1', null, 'Click the button!'),
React.createElement('button', {
id: 'main_button',
onClick: _handleClick
}, 'Click me')
);
}
```* __React JS__ (JSX):
```jsx
render() {
return;
Click the button!
Click me
}
```* __Vanilla react-dart__:
```dart
render() {
return react.div({'className': 'container'},
react.h1({}, 'Click the button!'),
react.button({
'id': 'main_button',
'onClick': _handleClick
}, 'Click me')
);
}
```* __OverReact__:
```dart
render() {
return (Dom.div()..className = 'container')(
Dom.h1()('Click the button!'),
(Dom.button()
..id = 'main_button'
..onClick = _handleClick
)('Click me')
);
}
```Let’s break down the OverReact fluent-style shown above
```dart
render() {
// Create a builder for a,
// add a CSS class name by cascading a typed setter,
// and invoke the builder with the HTML DOMand children.
return (Dom.div()..className = 'container')(// Create a builder for an
and invoke it with children.
// No need for wrapping parentheses, since no props are added.
Dom.h1()('Click the button!'),// Create a builder for a ,
(Dom.button()
// add a ubiquitous DOM prop exposed on all components,
// which Dom.button() forwards to its rendered DOM,
..id = 'main_button'
// add another prop,
..onClick = _handleClick
// and finally invoke the builder with children.
)('Click me')
);
}
```
## DOM components and props
All [react-dart][react-dart] DOM components _(`react.div`, `react.a`, etc.)_ have a
corresponding `Dom` method _(`Dom.div()`, `Dom.a()`, etc.)_ in OverReact.```dart
ReactElement renderLink() {
return (Dom.a()
..id = 'home_link'
..href = '/home'
)('Home');
}ReactElement renderResizeHandle() {
return (Dom.div()
..className = 'resize-handle'
..onMouseDown = _startDrag
)();
}
```* OverReact DOM components return a new `DomProps` builder, which can be used
to render them via our [fluent interface](#fluent-style-component-consumption)
as shown in the examples above.
* `DomProps` has statically-typed getters and setters for all HTML attribute props.
* The `domProps()` function is also available to create a new typed Map or a typed view into an existing Map. Useful for manipulating DOM props and adding DOM props to components that don’t forward them directly, or to access a DOM prop from a plain map in a lifecycle method as shown below.
```dart
@override
void componentDidUpdate(Map prevProps, Map prevState, [dynamic snapshot]) {
// Say you want to compare the previous / current value of `DomProps.title` here...
final titleChanged = domProps(prevProps).title != props.title;
}
```
## Component Formatting
> __A note on dart_style:__
>
> Currently, [dart_style (dartfmt)](https://github.com/dart-lang/dart_style) decreases the readability of components
> built using [OverReact's fluent-style](#fluent-style-component-consumption).
> See https://github.com/dart-lang/dart_style/issues/549 for more info.
>
> We're exploring some different ideas to improve automated formatting, but for the time being, we __do not recommend__ using dart_style with OverReact.
>
> However, if you do choose to use dart_style, you can greatly improve its output by using trailing commas in children argument lists:
>
> * dart_style formatting:
> ```dart
> return (Button()
> ..id = 'flip'
> ..skin =
> ButtonSkin.vanilla)((Dom.span()
> ..className = 'flip-container')((Dom.span()..className = 'flipper')(
> (Dom.span()
> ..className =
> 'front-side')((Icon()..glyph = IconGlyph.CHEVRON_DOUBLE_RIGHT)()),
> (Dom.span()
> ..className =
> 'back-side')((Icon()..glyph = IconGlyph.CHEVRON_DOUBLE_LEFT)()))));
> ```
> * dart_style formatting, when trailing commas are used:
> ```dart
> return (Button()
> ..id = 'flip'
> ..skin = ButtonSkin.vanilla)(
> (Dom.span()..className = 'flip-container')(
> (Dom.span()..className = 'flipper')(
> (Dom.span()..className = 'front-side')(
> (Icon()..glyph = IconGlyph.CHEVRON_DOUBLE_RIGHT)(),
> ),
> (Dom.span()..className = 'back-side')(
> (Icon()..glyph = IconGlyph.CHEVRON_DOUBLE_LEFT)(),
> ),
> ),
> ),
> );
> ```### Guidelines
To help ensure your OverReact code is readable and consistent, we've arrived at the following formatting rules.
* __ALWAYS__ place the closing builder parent on a new line.
_Good:_
```dart
(Button()
..skin = ButtonSkin.SUCCESS
..isDisabled = true
)('Submit')
```_Bad:_
```dart
(Button()
..skin = ButtonSkin.SUCCESS
..isDisabled = true)('Submit')
```* __ALWAYS__ pass component children on a new line with trailing commas and 2 space indentation.
_Good:_
```dart
Dom.div()(
Dom.span()('nested component'),
)
``````dart
Dom.div()(
Dom.span()('nested component A'),
Dom.span()('nested component B'),
)
```_Bad:_
```dart
// Children are not on a new line; in most cases,
// this makes it difficult to quickly determine nesting.
Dom.div()(Dom.span()('nested component'), Dom.span()('nested component'))
``````dart
// With nested hierarchies, continuation indents can quickly result
// in a "pyramid of Doom"
Dom.div()(
Dom.ul()(
Dom.li()(
Dom.a()('A link!')
)
)
)
``````dart
// Omitting trailing commas makes it a pain to rearrange lines
Dom.div()(
Dom.span()('nested component A'),
Dom.span()('nested component B')
)
Dom.div()(
Dom.span()('nested component B') // ugh, need to add a comma here...
Dom.span()('nested component A'),
)
```* __AVOID__ passing children within lists; lists should only be used when the number/order of the children are dynamic.
_Good:_
```dart
Dom.div()(
Dom.span()('nested component'),
Dom.span()('nested component'),
)
``````dart
var children = [
Dom.div()('List of Items:'),
]..addAll(props.items.map(renderItem));return Dom.div()(children)
```_Bad:_
```dart
Dom.div()([
(Dom.span()..key = 'span1')('nested component'),
(Dom.span()..key = 'span2')('nested component'),
])
```* __AVOID__ specifying more than one cascading prop setter on the same line.
_Good:_
```dart
(Dom.div()
..id = 'my_div'
..className = 'my-class'
)()
```_Bad:_
```dart
(Dom.div()..id = 'my_div'..className = 'my-class')()
```## Building custom components
Now that we’ve gone over how to [use the `over_react` package in your project](#using-overreact),
the [anatomy of a component](#anatomy-of-an-overreact-component) and the [DOM components](#dom-components-and-props)
that you get for free from OverReact, you're ready to start building your own custom React UI components.1. Start with one of the [component boilerplate templates](#component-boilerplate-templates) below
(Or, use OverReact's [code snippets for WebStorm/IntelliJ and VsCode](snippets/README.md)).
* [Component](#component-boilerplate) _(props only)_
* [Stateful Component](#stateful-component-boilerplate) _(props + state)_
2. Fill in your props and rendering/lifecycle logic.
3. Consume your component with the fluent interface.
4. Run [the app you’ve set up to consume `over_react`](#using-overreact)```bash
$ webdev serve
```_That’s it! Code will be automatically generated on the fly by the [builder]!_
> __Check out some custom [component demos] to get a feel for what’s possible!__
### Component Boilerplate Templates
* #### [WebStorm/IntelliJ and VsCode Snippets](snippets/README.md)
* #### Component Boilerplate
```dart
import 'package:over_react/over_react.dart';
part 'foo_component.over_react.g.dart';UiFactory Foo = castUiFactory(_$Foo); // ignore: undefined_identifier
mixin FooProps on UiProps {
// Props go here, declared as fields:
late bool isDisabled;
late Iterable items;
}class FooComponent extends UiComponent2 {
@override
Map get defaultProps => (newProps()
// Cascade default props here
..isDisabled = false
..items = []
);@override
dynamic render() {
// Return the rendered component contents here.
// The `props` variable is typed; no need for string keys!
}
}
```* #### Stateful Component Boilerplate
```dart
import 'package:over_react/over_react.dart';
part 'foo_component.over_react.g.dart';UiFactory Bar = castUiFactory(_$Bar); // ignore: undefined_identifier
mixin BarProps on UiProps {
// Props go here, declared as fields:
late bool isDisabled;
late Iterable items;
}mixin BarState on UiState {
// State goes here, declared as fields:
late bool isShown;
}class BarComponent extends UiStatefulComponent2 {
@override
Map get defaultProps => (newProps()
// Cascade default props here
..isDisabled = false
..items = []
);@override
Map get initialState => (newState()
// Cascade initial state here
..isShown = true
);@override
dynamic render() {
// Return the rendered component contents here.
// The `props` variable is typed; no need for string keys!
}
}
```* #### Function Component Boilerplate
```dart
import 'package:over_react/over_react.dart';
part 'foo_component.over_react.g.dart';UiFactory Foo = uiFunction(
(props) {
// Set default props using null-aware operators.
final isDisabled = props.isDisabled ?? false;
final items = props.items ?? [];
// Return the rendered component contents here.
// The `props` variable is typed; no need for string keys!
return Fragment()(
Dom.div()(items),
(Dom.button()..disabled = isDisabled)('Click me!'),
);
},
// The generated props config will match the factory name.
_$FooConfig, // ignore: undefined_identifier
);mixin FooProps on UiProps {
// Props go here, declared as fields:
bool? isDisabled;
Iterable? items;
}
```
### Component Best Practices
* __ALWAYS__ write informative comments for your component factories.
Include what the component relates to, relies on, or if it extends
another component._Good:_
```dart
/// Use the `DropdownButton` component to render a button
/// that controls the visibility of a child [DropdownMenu].
///
/// * Related to [Button].
/// * Extends [DropdownTrigger].
/// * Similar to [SplitButton].
///
/// See: .
UiFactory DropdownButton = castUiFactory(_$DropdownButton); // ignore: undefined_identifier
```_Bad:_
```dart
/// Component Factory for a dropdown button component.
UiFactory DropdownButton = castUiFactory(_$DropdownButton); // ignore: undefined_identifier
```
* __ALWAYS__ set a default / initial value for boolean `props` / `state` fields,
and document that value in a comment._Why?_ Without default prop values for bool fields, they could be
`null` - which is extremely confusing and can lead to a lot of
unnecessary null-checking in your business logic._Good:_
```dart
mixin DropdownButtonProps on UiProps {
/// Whether the [DropdownButton] appears disabled.
///
/// Default: `false`
bool isDisabled;/// Whether the [DropdownButton]'s child [DropdownMenu] is open
/// when the component is first mounted.
///
/// Determines the initial value of [DropdownButtonState.isOpen].
///
/// Default: `false`
bool initiallyOpen;
}mixin DropdownButtonState on UiState {
/// Whether the [DropdownButton]'s child [DropdownMenu] is open.
///
/// Initial: [DropdownButtonProps.initiallyOpen]
bool isOpen;
}DropdownButtonComponent
extends UiStatefulComponent2 {
@override
Map get defaultProps => (newProps()
..isDisabled = false
..initiallyOpen = false
);@override
Map get initialState => (newState()
..isOpen = props.initiallyOpen
);
}
```_Bad:_
```dart
mixin DropdownButtonProps on UiProps {
bool isDisabled;
bool initiallyOpen;
}mixin DropdownButtonState on UiState {
bool isOpen;
}DropdownButtonComponent
extends UiStatefulComponent2 {
// Confusing stuff is gonna happen in here with
// bool props that could be null.
}
```
* __AVOID__ adding `props` or `state` fields that don't have
an informative comment._Good:_
```dart
mixin DropdownButtonProps on UiProps {
/// Whether the [DropdownButton] appears disabled.
///
/// Default: `false`
bool isDisabled;/// Whether the [DropdownButton]'s child [DropdownMenu] is open
/// when the component is first mounted.
///
/// Determines the initial value of [DropdownButtonState.isOpen].
///
/// Default: `false`
bool initiallyOpen;
}mixin DropdownButtonState on UiState {
/// Whether the [DropdownButton]'s child [DropdownMenu] is open.
///
/// Initial: [DropdownButtonProps.initiallyOpen]
bool isOpen;
}
```_Bad:_
```dart
mixin DropdownButtonProps on UiProps {
bool isDisabled;
bool initiallyOpen;
}mixin DropdownButtonState on UiState {
bool isOpen;
}
```
#### Ignore Ungenerated Warnings Project-Wide
To avoid having to add `// ignore: uri_has_not_been_generated` to each
component library on the part/import that references generated code,
ignore this warning globally within analysis_options.yaml:```yaml
analyzer:
errors:
uri_has_not_been_generated: ignore
```Alternatively, `include` [workiva_analysis_options](https://github.com/Workiva/workiva_analysis_options)
which ignores this warning by default.
## Contributing
Yes please! ([__Please read our contributor guidelines first__][contributing-docs])
## Versioning
The `over_react` library adheres to [Semantic Versioning](https://semver.org/):
* Any API changes that are not backwards compatible will __bump the major version__ _(and reset the minor / patch)_.
* Any new functionality that is added in a backwards-compatible manner will __bump the minor version__
_(and reset the patch)_.
* Any backwards-compatible bug fixes that are added will __bump the patch version__.[component demos]: https://workiva.github.io/over_react/demos
[contributing-docs]: https://github.com/Workiva/over_react/blob/master/CONTRIBUTING.md
[builder]: https://github.com/Workiva/over_react/blob/master/lib/src/builder/README.md
[annotations]: https://github.com/Workiva/over_react/blob/master/lib/src/component_declaration/annotations.dart
[annotation]: https://github.com/Workiva/over_react/blob/master/lib/src/component_declaration/annotations.dart
[component_base.dart]: https://github.com/Workiva/over_react/blob/master/lib/src/component_declaration/component_base.dart[react-dart]: https://github.com/cleandart/react-dart
[react-js]: https://github.com/facebook/react
[react-js-tutorial]: https://reactjs.org/docs/getting-started.html[react.Component2]: https://pub.dev/documentation/react/latest/react/Component2-class.html
[ReactElement]: https://pub.dev/documentation/react/latest/react_client.react_interop/ReactElement-class.html[new-issue]: https://github.com/Workiva/over_react/issues/new
[gitter-chat]: https://gitter.im/over_react/Lobby[analyzer-plugin]: tools/analyzer_plugin/