react-common-admin
A react page container that works with react-parse to fetch data from server and display as table/gallery or customs component.
Table of content
- initCommonAdmin
- Basic Usage
- Props
- Document Props
- Collection Props
- View Component
- collection view Component ready to use
- View Component
- Document witout list
- DraggableTable example
- CustomTitle
- Document fields
- Collection fields
Installation
- First you need to install: Ant Design
2.2- Install react-common-admin npm i react-common-admin --save ```
3.3- Init react-common-admin
```jsx
// inside your root component
import
defaultDocumentMessages
/* notification default messages - You can pass a default notification messages*/const defaultDocumentMessages = onPostMessage: 'Created successfully' onPostFailedMessage: 'document - Created failed' onPutMessage: 'Update successfully' onPutFailedMessage: 'document - Update failed' onDeleteMessage: ' Deleted successfully' onDeleteFailedMessage: ' Deleted failed'
langDir
const langDir = 'ltr' // You can set 'rtl' or 'ltr'
customTitle
/* document customTitle- You can pass a function that get a props and return the title to diaplay in the document header*/const customTitle = { const data = state; const objectId schemaName titleKey = props let title = ''; const isNew = !objectId; if isNew title = `Create a New document` else let titleFromKey = titleKey && data ? datatitleKey : '' let hasTitle = titleFromKeylength title = `Edit document - `return title;}
setParams
/* If you want to persist the user work when the page is full reload, we need an access to URL params, pass setParams and setParams*/ seconst ar = { const href = `?=` const as = href Router}
getParams
import Router from 'next/router'; // You can use any Router service you want const getParams = { return Routerquery}
Basic Usage
You can use any inputs you want, not only from library fields
const getParams = function () { return Router.query }
//--- ntional confuratnmon a efoutese, a, sote })
import React from 'react';import CommonAdmin fields from 'react-common-admin' const DocFields = // See react-cross-form key: 'firstName' label: 'First Name' validators: presence: true length: minimum: 2 component: fieldsTextInput const TableField = key: 'objectId' title: 'Object Id' key: 'firstName' title: 'First Name' Component { return <div> <CommonAdmin ='Example' ='ExampleScreen' ='Example Screen' = = /> </div> ;}
Props
key | type | Description |
---|---|---|
title | string | title to dispaly |
targetName | string required |
react-parse targetName |
schemaName | string required |
react-parse schemaName |
functionName | string | react-parse functionName When you using clude code the delete from table is not enabled |
onVisibleDocumentsChanged | function | Function that be call when VisibleDocuments state is changedfetchExtraData |
documentProps | object required |
See documentProps |
collectionProps | object required |
See collectionProps |
openAsFullDoc | boolean default: true |
, set false if you want the document to open as a half screen |
paramSync | boolean default: true |
set false if you didnt want to sync visibleDocument with url parms |
refreshExtraDataOnRefresh | boolean default: true |
When true, react-parse will fetch data to all extra data and not only document/collection |
documentProps
key | type | Description |
---|---|---|
fields | array required |
we use react-cross-form Options that not from react-cross-form: 1- You can add to each field an InitialValue (work only with new document) |
wrapper | element | You can replace the default side modal wrapper , wrapper get this props { isOpen: bollean, onClose: function, title: string, children: react children } |
title | string | title to display |
customTitle | function | function that get {state, props} and return string as title |
parseDataBeforePost | function | optional - function that call with the data before post, (data, tableProps) => {return ({...data, {test: 1})} |
parseDataBeforePut | function | optional - function that call with the data before put, (data, tableProps, objectId, docFetchProps) => {return ({...data, {test: 1})} |
saveOnBlur | boollean | default is true, run react-parse put when input is blur |
messages | object | You can display a custom message, this data will pass to your notification service, see initCommonAdmin |
onPostFinished | function | react-parse onPostFinished |
onPutFinished | function | react-parse onPutFinished |
onDeleteFinished | function | react-parse onDeleteFinished |
showDeleteButton | boolean | |
showCloseButton | boolean | |
viewComponent | element | default is DocForm but you can pass your custom component, See document viewComponent props for more information |
stayOpenAfterPost | boolean | Set true if you want to leave the document open after post successfully |
initialValue | object | You can pass object and new document will create with this initialValue, see react-parse initialValue |
document viewComponent
How to pass your component ?
import MyDocView from './MyDocView'...return <CommonAdmin ... = ...
What props you will get ?
key | type | Description |
---|---|---|
fetchProps |object|S- see [react-parse fetchProps](https://github.com/doronnahum/react-parse#fetchprops)|
;
onClose|, - function |C- call to close modal (relevant when the document wrapper is modal)
isOpen |- boolean| True when th - is modal is open
objectId|, - string| Parse document id, - empty on new document
saveOnBlur| boolean| The value from your CommonAdmin>documentProps configuraion
fields|, - array|The value from your CommonAdmin>documentProps configuraion|
fieldsOptions |object|F- fetchExtraData is pass to document as fieldsOptions - pass only for fields that contain a targetName.
, the key for each value in fieldsOptions is the targetName
extraData | object| all fetchExtraData results
...||Any other parameters you set inside documentProps will pass to your viewComponent
document - wrapper
The default wrapper is a side modal bot you can use our modal like that
import Modal from 'react-coomon-admin...return (<CommonAdmin ... documentProps={{ wrapper: Modal }} .../>
And you can customize The wrapper like that
import Modal from './rect-some-modal-component' Component { const isOpen onClose modalId = thisprops return <Modal = = > children </Modal> } Component { return <CommonAdmin ... = ... /> } ... all other parameters from your documentProps configuration
document - initialValue
You have to options to set to a new document an initialValue, as you can see in the example, one option is inside the document fields for each field and the other option is inside the documentProps
const DocFields = key: 'title' label: 'Title' component: TextInput initialValue: 'The article title initialValue' key: 'body' label: 'Body' component: TextInput <CommonAdmin ... =
collectionProps
key | type | Description |
---|---|---|
fields | array required |
[{key: 'objectId', title: 'Object Id', search: true, formatter: (cell, row) => {}} ] |
title | string | title to display |
limit | number | react-parse limit value , default is 10 |
skip | number | react-parse skip value , default is 0, |
order | string | react-parse string, default is 'createdAt' |
query | object | react-parse query, default is {} |
dataHandler | funciton | react-parse dataHandler |
onLimitChanged | funciton | if you didn't pass this handlers than your limit is used as initial value and react-common-admin will handle the changes |
onSkipChanged | funciton | optional - only if you want to override our function and take the control of this value |
onOrderChanged | funciton | optional - only if you want to override our function and take the control of this value |
onPagination | funciton | optional - only if you want to override our function and take the control of this value |
onQueryChanged | funciton | optional - only if you want to override our function and take the control of this value |
tableProps | object | any props you want to pass to the viewComponent |
... | Any other parameters you set inside collectionProps will pass to your viewComponent | |
viewComponent | element | See collention viewComponent propsviewComponent |
collention viewComponent
How to pass your component ?
import MyTablView from './MyDocView'...return <CommonAdmin ... = ...
What props you will get ?
key | type | Description |
---|---|---|
extraData | object | All fetchExtraData results |
fetchProps | object | See react-parse fetchProps |
fields | array | The value from your CommonAdmin>collentionProps configuraion |
onCreateNewDoc | function | Call this and document modal will display, you can pass as first parameter any data you want and document will get this on props.dataFromCollection |
onEditDoc | function | Call this with objectId and document modal will display to edit, you can pass as seconde parameter any data you want and document will get this on props.dataFromCollectio |
skip | number | Current skip value |
limit | number | Current limit value |
onLimitChanged | function | Call to set new limit value onLimitChanged(20) |
onSkipChanged | function | Call to set new skip value onSkipChanged(20) |
onOrderChanged | function | Call to set new order value onOrderChanged('createdAt') |
onPagination | function | Call to set new limit and skip value onPagination(page, limit) We caliculate skip from page like that: skip = (page - 1) * limit |
... | Any other parameters you set inside collentionProps will pass to your viewComponent |
Table
The default collection viewComponent is Table You can pass inside collentionProps tableProps object to customize some things in the table
...return <CommonAdmin ... = ...
tableProps options
key | type | Description |
---|---|---|
renderAddBtn | function | funciton that get all table props and need to return a button |
customOnEdit | function | funciton that be call when user click on edit button, with the row and all table props (rowObjectId, tableProps) => {...} |
renderAddBtn | function | funciton that be call when user click on add button |
disabledDelete | boolean | Set true to hide the delete button |
renderAddBtn exmple
return <CommonAdmin
DraggableTable
By default collection render a table, if you want you can pass as viewComponent a DraggableTable, it is like the regular table with the ability to drag row and change value in the DB base user drag and drop
import CommonAdmin DraggableTable from 'react-common-admin';<CommonAdmin... =
document witout list
Need only a documet ?
See this example
import React from 'react';import CommonAdmin StaticDoc from 'react-common-admin'import DocFields from './config'; Component { return <div> <CommonAdmin ='Member' ='ProfileSettings' ='Profile Settings' = //--------------->!important documentProps= fields: DocFields objectId: 'eviegCusH8' wrapper: StaticDoc //--------------->!important messages: onPostMessage: 'Create successfully' onPostFailedMessage: 'Create failed' onPutMessage: 'Update successfully' onPutFailedMessage: 'Update failed):' onDeleteMessage: 'Deleted successfully' onDeleteFailedMessage: 'Deleted failed' { 'title' } fetchExtraData= schemaName: 'City' targetName: 'CityDropDown' /> </div> ; }
customTitle
When you init with customTitle you can use it like that:
import { CommonAdmin, customTitle } from 'react-common-admin'
<CommonAdmin
schemaName='Example'
targetName='ExampleScreen'
title='Example Screen'
documentProps={{
fields: DocFields, // Define this fields you want to render
customTitle: customTitle,
titleKey: 'firstName',
include: 'imageFromMedia'
...
}}
Document fields
react-common-admin fields
import fields from 'react-common-admin'
available fields
const TextInput NumberInput MobileInput UploadFile DateTime Pointer DropDown ObjectsDropDown AddressAutoComplete GeoLocationMapView AddressWithMapView Tags ArrayOfPointer ArrayOfPointerTableView TextArea } = fields;
Fields Examples
TextInput
key: 'firstName' label: 'First Name' validators: presence: true length: minimum: 2 component: fieldsTextInput helpText: 'Please tell as what is your name'
TextArea
key: 'info' label: 'Whe are you' component: fieldsTextArea helpText: 'I am example of a textArea'
MobileInput
We use 'libphonenumber-js to validate the phone number import { isValidNumber } from 'libphonenumber-js'
key: 'mobile' label: 'Mobile' { let errors = if!value || value === '' errors else if! errors return errors } component: fieldsMobileInput
UploadFile
- Upload file to parse File Field
key: 'image' label: 'Image as Parse File Example' component: fieldsUploadFile validators: presence: true
- Upload file and save as url sring
key: 'urlString' // Example how to upload an image an set a url string and not parse file object; label: 'Image - image as string example' component: fieldsUploadFile validators: presence: true { return resdataurl }
SelectFromMedia
- Select file from media screen and save as pointer to media collection
key: 'imageFromMedia'label: 'imageFromMedia - image as pointer to Media'component: fieldsSelectFromMediaasPointer: truevalidators: presence: true
- Select file from media screen and save as string url
key: 'imageFromMediaAsString'label: 'imageFromMediaAsString - image as string from Media'component: fieldsSelectFromMediavalidators: presence: true
NumberInput
key: 'age' label: 'Age - number input example' component: fieldsNumberInput
DateTime
key: 'birthday' label: 'Birthday' component: fieldsDateTime
Pointer
key: 'city' label: 'City - pointer fields example' component: fieldsPointer schemaName: 'City' targetName: 'CityDropDown' labelKey: 'name'
ArrayOfPointer
drop down with multi select
key: 'roles' label: 'Roles' component: fieldsArrayOfPointer schemaName: 'City' targetName: 'CityDropDown' labelKey: 'name'
ArrayOfPointerTableView
Table with switch button in each row
key: 'cities' label: 'Cities' component: fieldsArrayOfPointerTableView schemaName: 'City' targetName: 'CityDropDown' labelKey: 'name'
DropDown
select string from array of static options
key: 'favoriteColor' label: 'Favorite Color - dropDown static options example - string value' component: fieldsDropDown options: key: 'red' label: 'red' key: 'green' label: 'green' key: 'blue' label: 'blue' key: 'pink' label: 'pink' <p =>label</p>
ObjectsDropDown
select object from array of static options
key: 'favoritePhone' label: 'Favorite Phone - dropDown static options example - object value' component: fieldsObjectsDropDown valueKey: 'model' // default is key labelKey: 'fullName' // default is label options: company: 'Samsung' OS: 'Android 8' model: 'Galaxy S9 Plus' fullName: 'Samsung Galaxy S9 Plus' company: 'Samsung' OS: 'Android 8' model: 'Galaxy S9' fullName: 'Samsung Galaxy S9' company: 'Huawei' OS: 'Android 8.1' model: 'P20 Pro' fullName: 'Huawei P20 Pro'
AddressAutoComplete
input with autocomplete off location
key: 'address' label: 'Address' component: AddressAutoComplete accessToken: envConfigMAP_BOX_ACCESS_TOKEN
AddressWithMapView
address string and geoLocation at the same document
key: 'group-address' addressFieldKey: 'address' locationFieldKey: 'location' component: AddressWithMapView group: key: 'address' label: 'Address' component: AddressAutoComplete accessToken: envConfigMAP_BOX_ACCESS_TOKEN key: 'location' label: 'Location' component: GeoLocationMapView accessToken: envConfigMAP_BOX_ACCESS_TOKEN
Tags
key: 'tags' label: 'Tags' component: Tags // Good for array of string validators: presence: true length: minimum: 2 helpText: 'Set tags to help the search engine what you want in the future'
Collection Fields
Each field need to include a key and title
- key - The key to data inside the data response from the server
- title - The title to display in the table header
- search - Set true if you want to include this field when user type inside the search input
- formatter - Pass function if you want to manipulate the value to display (like in Date value)
formatter
Your function will get (cell, row, field, extraData)
- cell - The value of this field in the data base
- row - The all document data {objectId...}
- field - Your field coniguration {key : '..', titiel: '...', formatter... }
- extraData - All extraData , this very helpful with pointer fields
This formatter for the collection fields document formatter is different, check react-cross-form formatter for more details
formatter examples
const imgForamtter = { if cell && cellurl return <img = =/> return <p>No image</p>}
Before you create a formatter, check this list, maybe have something redey for you
Table Fields exmpels
import formatters from 'react-common-admin'
formatter = function(fieldValue, docData, fieldConfig, extraData){ return 'your view'}
string
key: 'objectId' title: 'Object Id' search: true
### img
key: 'image' title: 'Image' formatter: formattersimageFormatter
Pointer with include
key: 'partner' title: 'Account' { iftypeof cell === 'object' const objectId name = cell return <p>name || objectId</p>; else return <p></p> }
### Array
key: 'roles' title: 'Roles' formatter: formattersarrayFormatter
Array of Pointers
When to use? when the response from server is like that: ['A12365','Ddck344'] and you want to display somting like that: Red,Green
{
key: 'verticals',
title: 'Verticals',
pointerTo: 'VerticalDropDown',
displayKey: 'name',
formatter: formatters.arrayOfPointerDisplay,
},
/*
In this example, our additional data include this:
<CommonAdmin
fetchExtraData={[
{schemaName: 'Vertical', targetName: 'VerticalDropDown'},
}]
*/
Action Button
If you want to show in the table action button, at this to collection fields
key: 'actionBtn' actionBtn: true onOrderChanged|funciton|onPagination|funciton|onQueryChanged|funciton|tableProps|object| any props you want to pass to the viewComponent### collention viewComponent props------```jsx{ fetchProps - see react-parse fetchProps fields - array dataHandler - see react-parse dataHandler (clodeCode) extraData - all fetchExtraData results title - string onCreateNewDoc- function - call this and document modal will display, you can pass as first parameter any data you want and document will get this on props.dataFromCollection onEditDoc- function - call this with objectId and document modal will display to edit, you can pass as seconde parameter any data you want and document will get this on props.dataFromCollectio skip - number limit - number // function to call when you want to set a new value onLimitChanged: (limit: number) => {...} onSkipChanged: (skip: number) => {...} onOrderChanged: (order: string => {...} onQueryChanged: (query: object) => {...} onPagination: (page: number, pageSize: number) => {...} ... all other parameters from your collectionProps configuration}
collention - tableProps options
key | type | Description |
---|---|---|
renderAddBtn | function | funciton that get all table props and need to return a button |
customOnEdit | function | funciton that be call when user click on edit button, with the row and all table props (rowObjectId, tableProps) => {...} |
renderAddBtn example | ||
disabledDelete | boolean | Set true to hide the delete button |
{const productTypes = || const onSelect = menuItem resreturn <Dropdown = > <Button => Add <Icon ="down" /> </Button> </Dropdown>}......<CommonAdmin...
react-parse fetchProps
see full details in react-parse docs {data, error, status, info. isLoading, refresh, cleanData, put, post, deleteDoc, updateField}
Need only a documet witout list?
See this example
import React from 'react';import CommonAdmin StaticDoc from 'react-common-admin'import DocFields from './config'; Component { return <div> <CommonAdmin ='Member' ='ProfileSettings' ='Profile Settings' = //--------------->!important documentProps= fields: DocFields objectId: 'eviegCusH8' wrapper: StaticDoc //--------------->!important messages: onPostMessage: 'Create successfully' onPostFailedMessage: 'Create failed' onPutMessage: 'Update successfully' onPutFailedMessage: 'Update failed):' onDeleteMessage: 'Deleted successfully' onDeleteFailedMessage: 'Deleted failed' { 'title' } fetchExtraData= schemaName: 'City' targetName: 'CityDropDown' /> </div> ; }
DraggableTable example
By default collection render a table, if you want you can pass as viewComponent a DraggableTable, it is like the regular table with the ability to drag row and change value in the DB base user drag and drop
import CommonAdmin DraggableTable from 'react-common-admin';<CommonAdmin... =
customTitle
When you init with customTitle you can use it like that:
import { CommonAdmin, customTitle } from 'react-common-admin'
<CommonAdmin
schemaName='Example'
targetName='ExampleScreen'
title='Example Screen'
documentProps={{
fields: DocFields, // Define this fields you want to render
customTitle: customTitle,
titleKey: 'firstName',
include: 'imageFromMedia'
...
}}
special situations
Want to create a new document only if he contains a Unique key?
In this example, we want to enable new document only if there is no another document in this collection with this code
import fields util from 'react-common-admin';const DocFields = key: 'code' label: 'Code' // validators: { presence: true, length: { minimum: 3 } }, { const validators = presence: true length: minimum: 3 ; return util } component: TextInput key: 'name' label: 'Name' validators: presence: true length: minimum: 2 component: TextInput
Need to keep another collection updating in each change ?
// Option 1// Sync by react-parse refresh collection<CommonAdmin ='ItemType' = =
// Option 2 // Use on Fetch end callback
<CommonAdmin =