Giter Site home page Giter Site logo

vicrodri / halstack-react-hal Goto Github PK

View Code? Open in Web Editor NEW

This project forked from dxc-technology/halstack-react-hal

1.0 1.0 0.0 805 KB

A library of high-order components for building API-driven SPAs with React

License: Apache License 2.0

HTML 8.58% JavaScript 89.60% CSS 1.82%

halstack-react-hal's Introduction

Halstack React HAL

Halstack React HAL is an npm library of reusable React components. It brings together two different responsibilities:

We have other libraries that will help you handling these responsibilities individually (Halstack Client / Halstack React). Halstack React HAL uses them under the hood, but it is a higher level abstraction that puts both responsibilities together using the most common association patterns.

For example, collection resources are often associated with tables, and there are a lot of semantics in the standards described by the DXC API guidelines for collections (sorting, paginating...) that could be associated with UI interactions (clicking a table header for sorting, clicking pages for paginating)

Usage

Halstack React HAL is distributed as an npm library. In order to use it in an existing project, you must install it first. You also need to install styled-components and Halstack React CDK, which are peer dependencies.

npm install @dxc-technology/halstack-react-hal styled-components @dxc-technology/halstack-react

The library provides the following components and hooks to be used in your React application:

Components

Hooks

HalTable Component

Hal Table Usage

import { HalTable } from "@dxc-technology/halstack-react-hal";

Hal Table Props

Name Default Description
collectionUrl: string The URL of the collection resource to be used for the table. Required
headers: Object Contains the http headers to be sent along with the http requests to the collectionUrl. Optional
asyncHeadersHandler: ()=>Promise<obj> Async function that will be executed right before every http request in order to retrieve dynamic headers. It must return a promise that resolves into an object with the keys and values of the headers. These headers will be merged with the ones indicated in the headers prop.Optional
itemsPerPage: number 5 The amount of items to be displayed per page. Will be used to calculate the _start and _num query parameters that will be sent to the collection for pagination. Optional
columns: array<obj> [] Array of objects specifying the columns to be displayed in the table. Each object has:
- header: Column label to be place at the table header.
- displayProperty: The name of the property in the items summary to be rendered for this column in the table.
- sortProperty: The name of the property in the items summary to be used for sorting the table.
- onClickItemFunction: Callback function that will be executed when the user clicks an item in that column. The collection item will be passed to this function when executed.
- mapFunction: Callback function that must return the value to be rendered in that column for a specific item. The item will be passed to this function as a parameter.

HAL Table Example

import React from "react";
import { HalTable } from "@dxc-technology/halstack-react-hal";

export default () => {
  return (
    <HalTable
      collectionUrl={"https://..."}
      columns={[
        {
          header: "Username",
          displayProperty: "username",
          sortProperty: "username"
        },
        {
          header: "Status",
          displayProperty: "status",
        },
        {
          header: "Enabled",
          displayProperty: "enabled",
        },
      ]}
    ></HalTable>
  );
};

HalAutocomplete Component

Hal Autocomplete Usage

import { HalAutocomplete } from "@dxc-technology/halstack-react-hal";

Hal Autocomplete Props

Name Default Description
url: string The URL of the collection resource to be used for the table. Required
headers: Object Contains the http headers to be sent along with the http requests to the collectionUrl. Optional
asyncHeadersHandler: ()=>Promise<obj> Async function that will be executed right before every http request in order to retrieve dynamic headers. It must return a promise that resolves into an object with the keys and values of the headers. These headers will be merged with the ones indicated in the headers prop.Optional
propertyName: string Name of the property to be used for filtering the data

In addition to these component-specific properties you will also have all the properties of the Text field component that can be found on its site

HalAutocomplete Component Example

import React, { useState, useEffect } from "react";
import {HalAutocomplete} from "@dxc-technology/halstack-react-hal";

export default () => {
  const [autocompleteValue, changeAutocompleteValue] = useState("")
  const onChange = (newValue) => {
    changeAutocompleteValue(newValue);
  };

  return (
    <div>

      <HalAutocomplete
        url="https://..."
        propertyName="full-name"
        label="Full Name"
        onChange={onChange}
        value={autocompleteValue}
      ></HalAutocomplete>
    </div>
  );
};

useHalResource Hook

useHalResource Usage

import { useHalResource } from "@dxc-technology/halstack-react-hal";

useHalResource Parameters

Name Default Description
url: string The URL of the resource. Required
headers: Object Contains the http headers to be sent along with the http requests to the url indicated in the url prop. Optional
asyncHeadersHandler: ()=>Promise<obj> Async function that will be executed right before every http request in order to retrieve dynamic headers. It must return a promise that resolves into an object with the keys and values of the headers. These headers will be merged with the ones indicated in the headers prop.Optional

useHalResource return array

The return value of this hook is an array with the following stateful variables. The property names in this table are just a reference, and you will need to identify them by item position. The table is sorted by item position within the array.

Name Description
resource: HalResource A Halstack Client's HalResource instance of the resource behind the url parameter.
  • It will be null until the resource is fetched.
  • It will be automatically refreshed if the execution of an interaction handler responds with an instance of the same resource.
requestStatus: 'idle' | 'fetching' | 'resolved' | 'rejected' | 'interaction' The status of the http request to the url parameter.
  • 'idle' before the request is triggered
  • 'fetching' after the request is triggered and the before we get a response.
  • 'resolved' after getting a successful response. Only if it contains a HAL resource.
  • 'rejected' after getting an error response. Or if response doesn't contain a HAL resource.
  • 'interaction' during the execution of an interaction handler.
requestError: string The error message in case the request gets rejected. It will be null before getting the response or if the response is successful and contains a HAL resource.
resourceInteractions: Object This is an object containing as many entries as interactions (_options.links) are available in the HAL resource. Each entry has the rel of the interaction as a key, and is a function that you can execute passing a payload as a parameter. Executing one of these functions will:
  • Make the http request associated to the given interaction.
  • Change the requestStatus to 'interaction', and then back to 'resolved' (even when the request fails).
  • Update the resource if the request responds with a new representation of the same resource.
  • Return a promise, so that you can handle the resolution or rejection manually.

useHalResource example

import React from "react";
import { useHalResource } from "@dxc-technology/halstack-react-hal";

export default () => {
  const [
    resource,
    requestStatus,
    requestError,
    resourceInteractions,
  ] = useHalResource({
    url: "https://...",
  });

  return <div>{requestStatus}</div>;
};

Contributing

Before opening new issues or pull requests, please refer to CONTRIBUTING.MD.

Development Setup

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.

The project is divided in two main folders. One is for the actual library, and the other one is a React application using the library.

Library

Contained in the lib folder.

cd lib

Install the library dependencies.

npm install

Run the build process into dist folder, detecting and automatically building changes in src.

npm run build:watch # or 'npm run build' if there is no need to watch for changes

Example Application

Contained in the app folder.

cd app # from the root folder

Install the application dependencies. The Halstack React CDK dependency is linked to the local lib folder. This one must have been previously built.

npm install

Start the application.

npm start # runs create-react-app dev server

Now, anytime you make a change to the library or the app, create-react-app will live-reload your local dev server so you can iterate on your component in real-time.

Running the tests

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.