1.0.50 • Published 3 years ago

framework-reactnative-component-lib v1.0.50

Weekly downloads
-
License
-
Repository
github
Last release
3 years ago

reactnative-component-lib

react native compent library

Table of Contents

About The Project

A component library is the fundation to build up an application. An interesting way to look at your components is by following the "atomic" design principle. If you look at following image, you see a visualization where you can build anything based on the base Atoms.

Built With

Getting Started

Prerequisites

  • As package manager it is recommended to use yarn, visit the website to find an installer or if you have npm installed you can use following command.
npm install yarn -g
  • This project is based upon react-native with the CLI (not expo), follow environment setup of react-native if this is the first time to have all dependencies installed. react-native

  • Have an android or iphone ad your disposal or a working simulator.

Installation

  1. Clone the repo
git clone https://github.com/WabcoEurope/reactnative-component-lib
  1. Install NPM packages
yarn install

Usage

Run the component documentation on a mobile device

  1. Build the storybook apk/ipa and launch the react-native debugger. Have a look in the package.json to find all preconfigured commands.
yarn run android
or
yarn run ios

you need to rerun this command each time new platfrom dependencies are added such as fonts, npm packages, ...

  1. To start working on an existing deployed apk you can launch react-native debugger with following command.
yarn run start

The react-native debugger will watch all changes done in the project and will hot-reload the UI in the application. There are some limitations where the session need to be restarted.

Run the component documentation in your browser

To build a web application we use a library called 'react-native-web', which transpiles react-native components into web components with the help of babel and webpack. 1. Build storybook static website

yarn run build-storybook-web

If you want a frequent build during development for react-native-web then you can use the watch command to inspect the changed files and auto trigger a new build.

yarn run watch-build-storybook-web
  1. The output of the build step can be found in the /public folder of your project. To being able to browse to it you can host the website with following command
yarn run watch-build-storybook-web

visit your storybook website on http://localhost:6010, to change the port you can edit it at /storybook-website/runwebsite/run.js

Development

Storybook

storybook is the tool that renders an interactive documentation page for the components. Components can be visualized programatorical by adding stories to the project. It is good first building block to use, abuse and visualize the components created in the library. To bring valuable documentation on the components we introduced 4 plugins into storybook.

Storybook actions

This plugin visualizes the action/event data that is sent by the component towards the consumer of the component. addons-actions.

Storybook knobs

This plugin shows how the consumer can interact with the component. Pass different values, colors or input data. Is a great way for testing the initial component design addons-knobs.

Storybook designs

This plugin makes a link between the storybook page and the figma designs created by the UX team. figma designs.

Storybook Addon-docs

This plugin generates a documentation page per story. For react-native we are currently limited to the basic form of documentation generation no mdx. More info on all capabilities can be found here.

Add a new component.

Component definition

  • The location to put components is /src/components/
  • Create a folder for your component starting with a lower cased lettre.
  • Minimum files to create is 'ComponentName.js' and 'componentName.style.js', keep in mind that the component files start with a captial letter all other locations use kamelCasing.
  • Add your component to the '/src/index.js' file to export your component and variable definitions.

This is a blueprint you should use to create a component.

//import main components in react.
import React, {useState} from 'react';
import {Text, TouchableHighlight} from 'react-native';
import PropTypes from 'prop-types';

//import for custom defined variables in the component library
import {colorModes} from '../../assets/constants/Colors';
import componentSizes from '../../assets/constants/Dimensions';

//import for styles.
import {styles} from './button.style';

//exports
export const buttonTypes = {primary: 'primary', secondary: 'secondary'};

//fixed varialbes
const availableButtonTypes = [buttonTypes.primary, buttonTypes.secondary];

//next comment block is used to write component documentation by storybook, it is the description field of a component
//the argument list needs to be present without ...props
//also respect the event signature onPress, onPressed to know when the event will be triggered. 

/**
 * Use the universal `Button` to perform an action in the system. The button contains different configurations to adapt height, colormode and visuaization type.
 */
const Button = ({type, size, colorMode, enabled, title, onPress}) => {
  const [pressed, setPressed] = useState(false);

  return (
    <TouchableHighlight
      style={[
        styles[colorMode].button.default
        ],
      ]}
      activeOpacity={1}
      onHideUnderlay={() => {
        if (enabled) {
          setPressed(false);
        }
      }}
      onShowUnderlay={() => {
        if (enabled) {
          setPressed(true);
        }
      }}
      underlayColor={
        enabled
          ? styles[colorMode].button[type].active.backgroundColor
          : styles[colorMode].button[type].disabled.backgroundColor
      }
      onPress={() => {
        if (enabled) {
          onPress();
        }
      }}>
      <Text
        style={[
          styles[colorMode].title.default,
          styles[colorMode].title[size],
          styles[colorMode].title[type][
            pressed ? 'active' : enabled ? 'default' : 'disabled'
          ],
        ]}>
        {title.toUpperCase()}
      </Text>
    </TouchableHighlight>
  );
};

//next comment is to generate property documentation in storybook on the 'Button' component. It takes into account types and default values. Each block above the property can describe extra information

// ... Button definition ...
Button.propTypes = {
   /**
   * Select the theme you want to render the button.
   */
  colorMode: PropTypes.oneOf(availableColorModes),
  type: PropTypes.oneOf(availableButtonTypes),
  size: PropTypes.oneOf(availableComponentSizes),
  enabled: PropTypes.bool,
  title: PropTypes.string.isRequired,
  onPress: PropTypes.func.isRequired,
};

Button.defaultProps = {
  colorMode: colorModes.lightMode,
  type: buttonTypes.primary,
  size: componentSizes.medium,
  enabled: true,
  title: 'Button Default',
};

export default Button;

Create a Default story for your component

  • Location to add stories is /src/stories/.stories.js
  • To add the story for react-native visualization you need to run following command. This will add your file to the /storybook/storyLoader.js
yarn run ioc-gen
  • Add following blueprint to start your story
import React from 'react';
import {Text} from 'react-native';

import {storiesOf} from '@storybook/react-native';
import {actions} from '@storybook/addon-actions';
import {text, withKnobs} from '@storybook/addon-knobs';

import {StoryWrapper} from './helpers/storyWrapper';

//style definition, as inline styling is not allowed
const styles = {
  text: {
    textAlign: 'center',
    color: 'red',
  },
};

//default config parameters for the component you want to test
const config = {
  dataDetectorType: 'email',
};

//https://www.npmjs.com/package/@storybook/addon-actions
const events = actions('onPress');

storiesOf('refStory', module)
  .addDecorator(StoryWrapper) //makes sure the component is centered and contains some margins in storybook
  .addDecorator(withKnobs)
  .addParameters({
    //change to component that is tested, this will scan the component for documentation generation, also figma link should be updated
    component: Text,
    title: 'text',
    //componentSubtitle: 'textcomponent',
    //description: 'The button description',
    design: {
      type: 'figma',
      url:
        'https://www.figma.com/file/ZUGRuns1ZTVamirxpJF5SY/Components?node-id=5%3A38',
    },
  })
  .add('Default', () => (
    <>
      //the default story should contain only defaults, how does it look without configuration!
      //the events objects is to see the event data in the actions addon //https://www.npmjs.com/package/@storybook/addon-actions
      //the text is an example on how knobs can be used to change the text of the textfield, //https://developer.aliyun.com/mirror/npm/package/@storybook/addon-knobs
      <Text {...events}>
        {text('knobsexample', 'no implementaiton yet')}
      </Text>
    </>
  ));
  • start the app to start developping the story
yarn run start
  • Complete the Default story on react-native, it supports hot reloading, debugging, etc
  • When finished the Default story, import the story file to react-native-web build file /storybook-website/main.js.
  • Trigger a react-native-web build to have a storybook website generated in the /public folder.
yarn run build-storybook-web
  • The component is in most cases compatible with react-native-web but can cause certain difficulties especially when react-native modules are used trough a npm package. There is the option to copy the source from the packages and put it in the /src/helpers/ (eg react-native-actions-sheet-web). react-native import is changed with react-native-web import this will transpile the component to a web module. This is only done on project scoped files and not on libraries thats why a copy can help as first try.

  • If the component really does not build with react-native-web, then we should create a mock story only for react-native-web. Name of the new mock sotry should then be .webstory.js and don't forget to change the import. There is one example of a mock story and a mock component to be able to generate the documentation properly calendar.webstory.js and calandarMock.js. It is required to attach a screenCapture to your mock component with a date of the screenCapture. An interesting tool to use is https://www.screentogif.com/. Whit this you can record different views of your component.

Create different stories for your component

Stories in storybook should highlight and test your components in all possible ways before it gets released. It should showcase all flavors and different possibilities. What is expected?

  • A story called Knobs which makes each variable available trough the knobs addon, the start should be as defualt as possible.
  • A story per existing variable that can be changed on the component, this with all possible input options if it are enums, booleans. Text should have at least a very long text representation and a short one.

Linting

When development is done you should run the lint commands to fix all space issues according to the spec.

yarn run lint --fix

Some issues cannot be fixed automagically, then you should go trough the list and fix each issue.

Now you are ready to publish your code and launch a pullrequest.

references

https://medium.com/@majirosstefan/exporting-react-native-storybook-components-as-static-web-app-d72024fbac19