Title

Global

Members

# constant react-utils-build

NodeJS script encapsulating Babel and Webpack compilation of this library, and of dependant projects. It also provides a working alternative for the npm link command.

Why? There are two reasons:

  1. The compilation of this library and its dependant projects follows the same logic: prepare the build output directory, removing any artifacts of previous builds, or creating the folder; bundle the isomorphic package with Webpack; compile the server-side code with Babel. Having the dedicated script which handles it saves us from copying necessary commands between different codebases.
  2. npm link command does not work well for many packages, including this library. The symbol links created by npm link easily break stuff in obscure ways. This script provides the option to watch and build a code into the specified directory. Thus, instead of linking @dr.pogodin/react-utils, or another dependency, into a host-package, this script allows to build it directly into host-package/node_modules/@dr.pogodin/react-utils/build folder, making any changes immediately available to the host package.

Usage

From this library codebase call it as

$ ./bin/build.js -h

From a host package codebase call it as

$ ./node_modules/.bin/react-utils-build -h

Here is the usage information output by these commands:

Usage: build [options]

Library build script

Options:
  --lib                     library build (default: false)
  -i, --in-dir <path>       input folder for the build (default: "src")
  -o, --out-dir <path>      output folder for the build (default: "build")
  -t, --build-type <type>   build type: development, production
  -w, --watch               build, watch, and rebuild on source changes
  --webpack-config <path>   path to the webpack config (default: "webpack.
onfig.js")
  -c, --copy-files <regex>  copy files matching the pattern into the build folder
  -h, --help                display help for command

To just build the package in development and production (with optimizations) modes we do:

$ ./bin/build -t development --lib
$ ./bin/build -t production --lib

These commands take the source code from src folder in the current directory, and build it to the build/development and build/production

  • output folders. -i and -o options allow to specify different input and output folders (/development or /production suffixes are append automatically to the output path specified by -o option, if --lib flag is set).

For a web app build, omit the --lib flag. Without it Babel part of the build will output directly to the specified output directory, and Webpack part of the build will output inside web-public folder inside it (we assume that a web app will publically share outcomes of the Webpack build, thus compiling the bundle to the dedicated folder allows to not expose the outputs of Babel compilation, intended for server-side use only).

BEWARE: To achieve folder structure described above this build script has to overwrite context and publicPath fields of the Webpack config you pass in.

--webpack-config option allows to specify the Webpack config file (by default it is expected to be inside the webpack.config.js file in the current working directory).

WARNING: The --watch option described below currently works only for Webpack part of the build. To enable it for Babel part requires a small update of Babel CLI: https://github.com/babel/babel/issues/10551

To use this script as an alternative for npm link, as explained above, add -w option, and use -o to specify the correct output path inside the target host package. For example, if a package A depends on the library B, and the library B is built into B/build folder by this build script, then the installation path of B modules inside A is (most probably) A/node_modules/B/build. You can install a local copy of B into A like this:

  • Build and pack B, doing inside its root:

    $ ./bin/build --lib -t development && ./bin/build --lib -t production
    $ npm pack
    

    It will product the file B-<version>.tgz inside B codebase.

  • Install the packed local version of B into A doing in the A's codebase root:

    $ rm -rf node_modules/B
    $ npm install /path/to/B/B-<version>.tgz
    
  • Now, inside B's codebase root start the watch & build of the library's development or production version (whatever you need for your testing and development case):

    $ ./bin/build --lib -t development -w -o /path/to/A/node_modules/B/build
    
  • Now you can start A and verify that any changes of B are propagated into A codebase. Once you done with your work, don't forget to revert A's dependency on the local B package back to its remote version (the local dependency is saved into package.json automatically, even if not opted in). You can do it by $ npm install --save B@<version>, or just reverting the change package.json manually or with your version control.

If you know what you are doing, most probably you do not need all these steps, and just running

$ /path/to/B/bin/build --lib -t development -w -o /path/to/A/node_modules/B/build

will work for you the same.

View Source bin/build.js, line 3

# constant react-utils-setup

$ ./node_modules/.bin/react-utils-setup [options] [libraries...]

The NodeJS script for library setup and upgrades. It helps to install library depedencies into a host package, using the same versions, and also saving them into the host's package.json.

This script installs each library from the whitespace separated list [libraries...]. After installing each library, it also installs into the host package:

  1. All development dependencies of that library, with the versions taken from the library's package.json. Installed dependencies are also saved as dev dependencies of the host package.

  2. All production dependencies, commong between the library and the host package, using the versions from the library's package.json. The versions are also saved into the host's package.json.

If no [libraries...] are specified, the latest version of @dr.pogodin/react-utils is installed by default.

With --just-fix-deps no libraries are installed, but their currently installed versions are checked, and their dependencies are installed into the host package in the way described above.

In other words, the command

$ ./node_modules/.bin/react-utils-setup

is equivalent to calling

$ npm install --save @dr.pogodin/react-utils@latest
$ npm install --save-dev dev-dep-1@version dev-dep-2@version ...
$ npm install --save prod-dep-1@version prod-dep-2@version ...

where the lists of dev and prod dependencies are formed in the way described above.

View Source bin/setup.js, line 3

Methods

# Button(propsopt)

import { Button } from '@dr.pogodin/react-utils';

Implements themeable buttons, and button-line links (elements which look like buttons, but behave as links) in the same uniform manner.

Under the hood, a <Button> instance is rendered as:

  1. <div> when the button is disabled. It helps to ensure exactly the same style of disabled buttons and button-like links.
  2. <Link> when to property is set. This takes care about internal and external links.
  3. <div> element, otherwise. <Link> component could also play the button role, but is more efficient to use <div> in this case.

Children: Component children, if any, are rendered as button content.

Parameters:
Name Type Attributes Description
props object <optional>

Component props.

active boolean <optional>

Set true to render the button as active, even if it is not active otherwise.

disabled boolean <optional>

Set true to disable the button.

enforceA boolean <optional>

When the button is rendered as <Link> component, this prop enforces it to be rendered as a simple <a> element (external link), rather than the React router's internal link. See <Link> documentation to learn when links are rendered as <a> by default.

onClick function <optional>

Click event handler.

onMouseDown function <optional>

Mouse down event handler.

openNewTab boolean <optional>

Set true to open link in the new tab.

replace boolean <optional>

When the button is rendered as <Link>, and the target URL is internal, this property tells that the new route should replace the last record in the browser's history, rather than to be pushed as a new entry into the history stack.

theme ButtonTheme <optional>

Ad hoc button theme.

to object | string <optional>

If specified, the button will be rendered as <Link> (if not disabled), and it will point to the specified location or URL.

... any <optional>
<repeatable>

Other properties of themeable components

View Source src/shared/components/Button/index.jsx, line 76

Example
import React from 'react';
import { Button } from '@dr.pogodin/react-utils';

export default function ButtonDemo() {
  return (
    <div>
      <Button onClick={() => alert('Button Clicked')}>Button</Button>
      <Button to="https://dr.pogodin.studio" openNewTab>
        Button-Like Link
      </Button>
      <Button disabled>Disabled Button</Button>
      <Button active>Forced-Active Button</Button>
    </div>
  );
}

# Checkbox(propsopt)

import { Checkbox } from '@dr.pogodin/react-utils';

The <Checkbox> component implements themeable checkboxes.

Parameters:
Name Type Attributes Description
props object <optional>

Component properties.

checked boolean <optional>

Checkbox value.

label string <optional>

Checkbox label.

onChange function <optional>

State change handler.

theme CheckboxTheme <optional>

Ad hoc theme.

... any <optional>
<repeatable>

Other properties of themeable components.

View Source src/shared/components/Checkbox/index.jsx, line 40

# client(Application)

import { client } from '@dr.pogodin/react-utils';

Prepares and launches the app at client side.

Parameters:
Name Type Description
Application object

Root application component

View Source src/client/index.jsx, line 9

# CodeSplit(props)

import { CodeSplit } from '@dr.pogodin/react-utils';

The <CodeSplit> component implements separation of an app part into separate code & style chunks (thus, allowing to split compiled app bundle into smaller lazy-loaded pieces).

Parameters:
Name Type Attributes Description
props object

Component properties.

chunkName string

Unique chunk name.

getComponentAsync function

Asynchronous function which resolves to the component to render in place of the <CodeSplit> (i.e. the component which we are splitting into a separate chunk), and uses dynamic import() with Webpack's webpackChunkName magic comment stating the same chunk name, as was specified via the chunkName property above.

getComponentServer function <optional>

A synchronous version of getComponentAsync() to be used during server-side rendering. If not provided, the server-side code will fallback to the asynchronous getComponentAsync(), which is sub-optimal. If provided, it will be called with a special resolveRequire function passed in as the only argument, which should be used to correctly resolve & require necessary modules, without Webpack being able to detect it and thus bundle them into client-side code (also see the example below).

placeholder function <optional>

Placeholder React component to render while the code for actual splitted component is being loaded.

... any <optional>
<repeatable>

Any other properties are passed as is into the splitted component.

View Source src/shared/components/CodeSplit/index.js, line 1

Example
// Assume <SampleComponent> is a React sub-tree we want to split into
// a stand-alone chunk. To achieve it, we use <CodeSplit> to declare
// an auxiliary <WrappedSampleComponent>, which we'll use everywhere
// in the code instead of <SampleComponent>. In result <SampleComponent>,
// and any other components in its sub-tree, not required directly in
// other chunks, will be placed into a dedicated chunk.

// WrappedSampleComponent.jsx
import { CodeSplit, webpack } from '@dr.pogodin/react-utils';

export default function WrappedSampleComponent(props) {
  return (
    <CodeSplit
      chunkName="sample-component"
      getComponentAsync={
        // NOTE: Use the normal comment block opening and closing at
        // the next line instead of / * and * / (whitespaces between
        // start and slash had to be added due to limitations of our
        // documentation setup).
        () => import(/ * webpackChunkName: 'sample-component' * / 'path/to/SampleComponent')
      }
      getComponentServer={
        // NOTE: You cannot just use the standard require() here, as it would
        // cause Webpack to bundle in required module into the current chunk,
        // instead of the split one. Thus, this workaround.
        (resolveRequire) => resolveRequire(__dirname, 'path/to/SampleComponent');
      }
      placeholder={() => <div>Optional Placeholder</div>}
      {...props}
    />
  );
}
import { Dropdown } from '@dr.pogodin/react-utils';

Implements a themeable dropdown list. Internally it is rendered with help of the standard HTML <select> element, thus the styling support is somewhat limited.

Parameters:
Name Type Attributes Default Description
props object <optional>

Component properties.

filter function <optional>

Options filter function. If provided, only those elements of options list will be used by the dropdown, for which this filter returns true.

label string <optional>

Dropdown label.

onChange string <optional>

Selection event handler.

options Array.<DropdownOption> | Array.<string> <optional>
[]

Array of dropdown options. For string elements the option value and name will be the same. It is allowed to mix DropdownOption and string elements in the same option list.

theme DropdownTheme <optional>

Ad hoc theme.

value string <optional>

Currently selected value.

... any <optional>
<repeatable>

Other theming properties

View Source src/shared/components/Dropdown/index.jsx, line 41

# Input(propsopt)

import { Input } from '@dr.pogodin/react-utils';

Themeable input field, based on the standard HTML <input> element.

Parameters:
Name Type Attributes Description
props object <optional>
label string <optional>

Input label.

theme InputTheme <optional>

Ad hoc theme.

... any <optional>
<repeatable>

Other theming properties

... any <optional>
<repeatable>

Any other properties are passed to the underlying <input> element.

View Source src/shared/components/Input/index.jsx, line 21

import { Link } from '@dr.pogodin/react-utils';

The <Link> component, and almost identical <NavLink> component, are auxiliary wrappers around React Router's <Link> and <NavLink> components; they help to handle external and internal links in uniform manner.

The <Link> (<NavLink>) component is rendered as a simple <a> element when:

  1. The link is absolute, i.e. starts with http:// or https://.
  2. The link points to an anchor, i.e. starts with # symbol.
  3. The link should be opened in a new tab (openNewTab property).
  4. Explicitly opted by the enforceA property.

Otherwise it is rendered as the usual React Router's <Link> (<NavLink>). Also in this case links to the current page scroll the page to its top when clicked.

Both <Link> and <NavLink> support all properties of the underlying React Router's components, along with some additional props:

Children: Child components are rendered as link's content.

Parameters:
Name Type Attributes Description
props object <optional>

Component properties.

className string <optional>

CSS classes to apply to the link.

disabled boolean <optional>

Disables the link.

enforceA boolean <optional>

true enforces rendering of the link as a simple <a> element.

keepScrollPosition boolean <optional>

If true, and the link is rendered as a React Router's component, it won't reset the viewport scrolling position to the origin when clicked.

onClick function <optional>

Event handler to trigger upon click.

onMouseDown function <optional>

Event handler to trigger on MouseDown event.

openNewTab boolean <optional>

If true the link opens in a new tab.

replace boolean <optional>

When true, the link will replace current entry in the history stack instead of adding a new one.

to string <optional>

Link URL.

activeClassName string <optional>

<NavLink> only: CSS class(es) to apply to rendered link when it is active.

activeStyle string <optional>

<NavLink> only: CSS styles to apply to the rendered link when it is active.

exact boolean <optional>

<NavLink> only: if true, the active class/style will only be applied if the location is matched exactly.

isActive function <optional>

<NavLink> only: Add extra logic for determining whether the link is active. This should be used if you want to do more than verify that the link’s pathname matches the current URL pathname.

location object <optional>

<NavLink> only: isActive compares current history location (usually the current browser URL). To compare to a different location, a custom location can be passed.

strict boolean <optional>

<NavLink> only: . When true, trailing slash on a location’s pathname will be taken into consideration when determining if the location matches the current URL. See the <Route strict> documentation for more information.

View Source src/shared/components/GenericLink/index.jsx, line 8

# MetaTags(propsopt)

import { MetaTags } from '@dr.pogodin/react-utils';

The <MetaTags> component is an auxiliary wrapper around react-helmet, which helps to inject meta tags (page title, a brief content description, and social media thumbnails) into generated pages.

When <MetaTags> are nested within the app's component tree, meta tags content injected by components encountered down the tree overrides tags injected by previously encountered <MetaTags> components.

Children: <MetaTags> children, if any, are rendered at the component's location. The context passes down all meta tag properties of parent <MetaTag> instances. These properties can fetched within children hierarchy in the following way, thus facilitating tags modification by children:

import { useContext } from 'react';
import { MetaTags } from '@dr.pogodin/react-utils';
export default function SampleComponent() {
  const { title, description, ...rest } = useContext(MetaTags.Context);
  // Do something with these props here, e.g. prefix the page title with
  // the component name:
  return (
    <MetaTags title={`Sample component - ${title}`} />
  );
}
Parameters:
Name Type Attributes Description
props object <optional>
description string <optional>

Page description to use in the description meta tag, and as a default description of Open Graph Tags.

image string <optional>

The absolute URL of thumbnail image to use in Open Graph Tags (twitter:image, and og:image). By default these tags are not injected.

BEWARE: It must be a complete, absolute URL, including the correct website domain and HTTP schema.

siteName string <optional>

The site name to use in twitter:site, and og:sitename tags. By default these tags are not injected.

socialDescription string <optional>

The site description to use in twitter:description and og:description meta tags. By default the value of description prop is used.

socialTitle string <optional>

The page title to use in twitter:title, og:title, and og:image:alt tags. By default the value of title prop is used. Also the og:image:alt tag is only injected if image prop is present.

title: string

The page name to use in the <title> tag. It is also used as the default value of socialTitle prop.

url string <optional>

The page URL to use in og:url tag. By default the tag is not injected.

View Source src/shared/components/MetaTags.jsx, line 7

Example
// Top-level app component.
import { MetaTags } from '@dr.pogodin/react-utils';
export default function ApplicationRoot() {
  return (
    <>
      <MetaTags
        title="Sample website title"
        description="Just the minimal example of MetaTags usage"
      >
      // The actual application content here.
      </>
  );
}
import { BaseModal, Modal } from '@dr.pogodin/react-utils';

The <Modal> component implements a simple themeable modal window, wrapped into the default theme. <BaseModal> exposes the base non-themed component. Children: Component children are rendered as the modal content.

Parameters:
Name Type Attributes Description
props object

Component properties.

onCancel function <optional>

The callback to trigger when user clicks outside the modal, or presses Escape. It is expected to hide the modal.

theme ModalTheme <optional>

Ad hoc theme.

... any <optional>
<repeatable>

Other theming properties

View Source src/shared/components/Modal/index.jsx, line 17

Example
import React, { useState } from 'react';
import { Button, Modal } from '@dr.pogodin/react-utils';

export default function ModalDemo() {
  const [visible, setVisible] = useState(false);
  return (
    <div>
      <Button onClick={() => setVisible(true)}>Show Modal</Button>
      {
        visible ? (
          <Modal onCancel={() => setVisible(false)}>
            This is a simple modal. Click outside, or press Escape to close
            it.
          </Modal>
        ) : null
      }
    </div>
  );
}
import { NavLink } from '@dr.pogodin/react-utils';

See Link documentation.

Parameters:
Name Type Attributes Description
props object <optional>

Component properties.

View Source src/shared/components/NavLink.jsx, line 5

# newBarrier() → {Promise}

import { newBarrier } from '@dr.pogodin/react-utils';

Creates a new async barrier: a Promise instance with its resolve method attached as .resolve field.

View Source src/shared/utils/index.js, line 46

Promise
Example
import { newBarrier } from '@dr.pogodin/react-utils';
(async () => {
  const barrier = newBarrier();
  setTimeout(() => barrier.resolve(), 5000);
  await barrier;
  console.log('This will be printed only after the timeout fires.');
})();

# PageLayout(propsopt)

import { PageLayout } from '@dr.pogodin/react-utils';
export default PageLayoutDemo() {
  return (
    <PageLayout>
      Page content.
    </PageLayout>
  );
}

Simple and themeable page layout. It keeps the main content centered in a column of limited width, which fills entire viewport on small screens (under $screen-md = 1024px size). At larger screens the column keeps $screen-md size, and it is centered at the page, surrounded by side panels, where additional content can be displayed.

Children: Component children are rendered as the content of main panel.

Parameters:
Name Type Attributes Description
props object <optional>

Component properties.

leftSidePanelContent Node <optional>

The content for left side panel.

rightSidePanelContent Node <optional>

The content for right side panel.

theme PageLayoutTheme <optional>

Ad hoc theme.

... any <optional>
<repeatable>

Other theming properties

View Source src/shared/components/PageLayout/index.jsx, line 7

# resolveRequire(base, path) → {object}

A specially wrapped require(), which is passed as an argument into the optional getComponentServer prop of <CodeSplit> component.

Parameters:
Name Type Description
base string

Path resolution base, you want to pass in __dirname value from the host module using <CodeSplit>.

path string

The path of module to require.

View Source src/shared/components/CodeSplit/ServerSide.jsx, line 24

Required module.

object

# ScalableRect(props)

import { ScalableRect } from '@dr.pogodin/react-utils';

The <ScalableRect> component implements container keeping given aspect ratio, while its width is altered.

Children: Component children are rendered as the component's content.

Parameters:
Name Type Attributes Default Description
props object
className string <optional>

CSS class for component container.

ratio string <optional>
1:1

Ratio of the rendered rectangle sides, in W:H form.

View Source src/shared/components/ScalableRect/index.jsx, line 5

# server(webpackConfig, optionsopt) → {Promise.<{expressServer: object, httpServer: object}>}

import { server } from '@dr.pogodin/react-utils`;
import webpackConfig from 'path/to/your/webpack.config';
server(webpackConfig);
// Web server is up, running, and serving the app specified by the provided
// Webpack config.

Creates and launches web-server for ReactJS application. Allows zero or detailed configuration, supports server-side rendering, and development tools, including Hot Module Reloading (HMR).

See ReactGlobalState for some additional notes related to SSR, access to incoming requests during SSR, etc.

Parameters:
Name Type Attributes Default Description
webpackConfig object

Webpack configuration used to build the frontend bundle. In production mode the server will read out of it context, publicPath, and a few other parameters, necessary to locate and serve the app bundle. In development mode the server will use entire provided config to build the app bundle in memory, and further watch and update it via HMR.

options object <optional>

Additional parameters.

Application Component <optional>

The root ReactJS component of the app to use for the server-side rendering. When not provided the server-side rendering is disabled.

beforeExpressJsError function <optional>

Asynchronous callback ((server) => Promise<boolean>) to be executed just before the default error handler is added to ExpressJS server. If the callback is provided and its result resolves to a truthy value, react-utils won't attach the default error handler.

beforeExpressJsSetup function <optional>

Asynchronous callback (`(server) => Promise) to be executed right after ExpressJS server creation, before any configuration is performed.

beforeRender BeforeRenderHook <optional>

The hook to run just before the server-side rendering. For each incoming request, it will be executed just before the HTML markup is generated at the server. It allows to load and provide the data necessary for server-side rendering, and also to inject additional configuration and scripts into the generated HTML code.

noCsp boolean <optional>

Set true to disable Content-Security-Policy (CSP) headers altogether.

cspSettingsHook function <optional>

A hook allowing to customize CSP settings for helmet's contentSecurityPolicy middleware on per-request basis.

If provided it should be a with signature:
(defaultSettings: object, req: object)object
which gets the default settings (also used without the hook), and the incoming request object. The hook response will be passed as options to the helmet contentSecurityPolicy middleware.

Currently, the default settings is the following object in production environment:

{
  directives: {
    defaultSrc: ["'self'"],
    baseUri: ["'self'"],
    blockAllMixedContent: [],
    fontSrc: ["'self'", 'https:', 'data:'],
    frameAncestors: ["'self'"],
    frameSrc: ["'self'", 'https://*.youtube.com'],
    imgSrc: ["'self'", 'data:'],
    objectSrc: ["'none'"],
    scriptSrc: ["'self'", "'unsafe-eval'", `'nonce-UNIQUE_NONCE_VALUE'`],
    scriptSrcAttr: ["'none'"],
    styleSrc: ["'self'", 'https:', "'unsafe-inline'"],
    upgradeInsecureRequests: [] // Removed in dev mode.
  }
}

It matches the default value used by Helmet with a few updates:

  • YouTube host is whitelisted in the frameSrc directive to ensure the YouTubeVideo component works.
  • An unique per-request nonce is added to scriptSrc directive to whitelist auxiliary scripts injected by react-utils. The actual nonce value can be fetched by host code via .nonce field of req argument of .beforeRender hook.
  • upgradeInsecureRequests directive is removed in development mode, to simplify local testing with http requests.
defaultLoggerLogLevel string <optional>
info

Log level for the default logger, which is created if no logger option provided.

devMode boolean <optional>

Pass in true to start the server in development mode.

favicon string <optional>

Path to the favicon to use by the server. By default no favicon is used.

https object <optional>

If provided, HTTPS server will be started, instead of HTTP otherwise. The object should provide SSL certificate and key via two string fields: cert, and key.

https.cert string <optional>

SSL Certificate.

https.key string <optional>

SSL key.

httpsRedirect boolean <optional>
true

Pass in true to enable automatic redirection of all incoming HTTP requests to HTTPS.

To smoothly use it at localhost you need to run the server in HTTPS mode, and also properly create and install a self-signed SSL sertificate on your system. This article is helpful: How to get HTTPS working on your local development environment in 5 minutes

logger Logger <optional>

The logger to use at server side. By default winston logger with console transport is used. The logger you provide, or the default winston logger otherwise, will be attached to the created ExpressJS server object.

onExpressJsSetup function <optional>

An async callback ((server) => Promise) to be triggered when most of the server configuration is completed, just before the server-side renderer, and the default error handler are attached. You can use it to mount custom API routes. The server-side logger can be accessed as server.logger.

port number | string <optional>
3000

The port to start the server on.

staticCacheSize number <optional>
1.e7

The maximum static cache size in bytes. Defaults to ~10 MB.

staticCacheController function <optional>

When given, it activates, and controls the static caching of generated HTML markup. When this function is provided, on each incoming request it is triggered with the request passed in as the argument. To attempt to serve the response from the cache it should return the object with the following fields:

  • key: string – the cache key for the response;
  • maxage?: number – the maximum age of cached result in ms. If undefined - infinite age is assumed.
maxSsrRounds number <optional>
10

Maximum number of SSR rounds.

ssrTimeout number <optional>
1000

SSR timeout in milliseconds, defaults to 1 second.

View Source src/server/index.js, line 76

Resolves to an object with created Express and HTTP servers.

Promise.<{expressServer: object, httpServer: object}>

# server/getDefaultCspSettings() → {Object}

import { server } from '@dr.pogodin/react-utils';
const { getDefaultCspSettings } from '@dr.pogodin/react-utils';

View Source src/server/server.js, line 58

A deep copy of default CSP settings object used by react-utils, with the exception of nonce-xxx clause in script-src directive, which is added dynamically for each request.

Object

# Throbber(propsopt)

import { Throbber } from '@dr.pogodin/react-utils';

Throbber is an "action in progress" indicator, which renders three bouncing circles as a simple pending activity indicator, and can be further themed to a certain degree.

Parameters:
Name Type Attributes Description
props object <optional>

Component properties.

theme ThrobberTheme <optional>

Ad hoc theme.

... any <optional>
<repeatable>

Other theming properties

View Source src/shared/components/Throbber/index.jsx, line 6

# withRetries(action, maxRetriesopt, intervalopt) → {Promise}

import { withRetries } from '@dr.pogodin/react-utils';

Attempts to perform given asynchronous action up to maxRetries times, with the given interval between attempts. If any attempt is successful, the result is returned immediately, with no further attempts done; otherwise, if all attempts fail, the result Promise rejects after the last attempt.

Parameters:
Name Type Attributes Default Description
action function
maxRetries number <optional>
5

Optional. Maximum number of retries. Defaults to 5 attempts.

interval number <optional>
1000

Optional. Interval between retries [ms]. Defaults to 1 second.

View Source src/shared/utils/index.js, line 73

Resolves to the result of successful operation, or rejects with the error from the latst failed attempt.

Promise
Example
import { withRetries } from '@dr.pogodin/react-utils';

let firstCall = true;

function sampleAction() {
  if (!firstCall) return 'success';
  firstCall = false;
  throw Error('The first call to this method fails');
}

withRetries(sampleAction).then(console.log);
// It will print 'success' after one second, once the second attempt
// is performed.

# WithTooltip(props)

import { WithTooltip } from '@dr.pogodin/react-utils';

Implements a simple to use and themeable tooltip component, e.g.

<WithTooltip tip="This is example tooltip.">
  <p>Hover to see the tooltip.</p>
</WithTooltip>

Children: Children are rendered in the place of <WithTooltip>, and when hovered the tooltip is shown. By default the wrapper itself is <div> block with display: inline-block.

Parameters:
Name Type Description
props object

Component properties.

tip React.node

– Anything React is able to render, e.g. a tooltip text. This will be the tooltip content.

theme WithTooltipTheme

Ad hoc theme.

View Source src/shared/components/WithTooltip/index.jsx, line 12

# YouTubeVideo(propsopt)

import { YouTubeVideo } from '@dr.pogodin/react-utils';

A component for embeding a YouTube video.

Parameters:
Name Type Attributes Description
props object <optional>

Component properties.

autoplay boolean <optional>

If true the video will start to play automatically once loaded.

src string <optional>

URL of the video to play. Can be in any of the following formats, and keeps any additional query parameters understood by the YouTube IFrame player:

  • https://www.youtube.com/watch?v=NdF6Rmt6Ado
  • https://youtu.be/NdF6Rmt6Ado
  • https://www.youtube.com/embed/NdF6Rmt6Ado
theme YouTubeVideoTheme <optional>

Ad hoc theme.

title string <optional>

The title attribute to add to the player IFrame.

View Source src/shared/components/YouTubeVideo/index.jsx, line 10

Type Definitions

# BeforeRenderHook(req, config) → {Promise.<{configToInject: object, extraScript: Array.<(object|string)>, initialState: object}>}

A hook for server's beforeRender option.

Parameters:
Name Type Description
req object

Incoming ExpressJS HTTP request, with some extra fields attached:

  • .nonce: string – CSP nonce for <script> tags, which should be added to the tags injected into the page to allow them to work.
config object

Application config that server wants to inject into generated HTML template.

View Source src/server/index.js, line 36

Promise resolving to the object with fields:

  • [configToInject] (Object) – Optional. The actual config object to inject into the generated page. If not provided, the config provided as argument will be injected as is.
  • [extraScripts] (Array of Objects and/or Strings) – Optional. Additional scripts to inject into the generated page. Each script given as a string will be injected as is in the end of generated document's <body>, just before the main application bundle. Each script given as an object is expected to have two fields: code holding the actual code to inject, and location specifying where to inject that code. The valid locations are exposed via the server.SCRIPT_LOCATIONS object. The scripts intended for the same location are injected in the order they are listed in the extraScript array.
  • [initialState] (Object) – Optional. Initial value of the global state.

server.SCRIPT_LOCATIONS

  • server.SCRIPT_LOCATIONS.BODY_OPEN – Right after the opening <body> tag.
  • server.SCRIPT_LOCATIONS.DEFAULT – In the end of <body> block, just before the main application bundle.
  • server.SCRIPT_LOCATIONS.HEAD_OPEN – Right after the opening <head> tag.
Promise.<{configToInject: object, extraScript: Array.<(object|string)>, initialState: object}>
object

# ButtonTheme

Button component theme: a map of CSS class names to append to button elements:

Properties:
Name Type Attributes Description
active string <optional>

to the root element of active button.

button string <optional>

to the root element of any button.

disabled string <optional>

to the root element of disabled button.

View Source src/shared/components/Button/index.jsx, line 62

object

# CheckboxTheme

Checkbox component theme: a map of CSS classes to append to its elements:

Properties:
Name Type Attributes Description
checkbox string <optional>

to the underlying checkbox <input> element.

container string <optional>

to the root checkbox element.

label string <optional>

to the checkbox label element.

View Source src/shared/components/Checkbox/index.jsx, line 26

object

Represents a single option inside Dropdown component.

Properties:
Name Type Attributes Description
name string <optional>

Option name (displayed in UI). If not given, the value is used as the name.

value string

Option value key (used inside the code).

View Source src/shared/components/Dropdown/index.jsx, line 8

object

Dropdown component theme.

Properties:
Name Type Attributes Description
arrow string <optional>

Class name for arrow element.

container string <optional>

Class name for the root dropdown element.

hiddenOption string <optional>

Class name for the "hidden option" element, which is rendered when dropdown value is undefined.

label string <optional>

Class name for label element.

option string <optional>

Class name for each option item element.

select string <optional>

Class name for the underlying <select> element.

View Source src/shared/components/Dropdown/index.jsx, line 83

object

# InputTheme

Input component theme.

Properties:
Name Type Attributes Description
container string <optional>

Class name for root component element.

input string <optional>

Class name for the underlying HTML <input> element.

label string <optional>

Class name for label element.

View Source src/shared/components/Input/index.jsx, line 37

object

# ModalTheme

Modal component theme.

Properties:
Name Type Attributes Description
container string <optional>

Class for modal container.

overlay string <optional>

Class for modal overlay (the background closing the page underneath the modal).

View Source src/shared/components/Modal/index.jsx, line 135

object

# PageLayoutTheme

PageLayout component theme.

Properties:
Name Type Attributes Description
container string <optional>

Class for the root container of page layout.

mainPanel string <optional>

Class for the main content panel.

sidePanel string <optional>

Class for each side panel.

leftSidePanel string <optional>

Class for the left side panel (in addition to .sidePanel, if also provided).

rightSidePanel string <optional>

Class for the right side panel (in addition to .sidePanel, if also provided).

View Source src/shared/components/PageLayout/index.jsx, line 56

object

# ThrobberTheme

Throbber theme.

Properties:
Name Type Attributes Description
container string <optional>

Class name to add to the throbber container.

circle string <optional>

Class name to add to each throbber circle.

View Source src/shared/components/Throbber/index.jsx, line 44