uno-react

uno-react npm uno-react Github Repo

Common functions, and hooks for React.

useClickOutside

This hook allows to call a given function when a click event occurs outside the component.

PARAMETERS
Type Description Optional
React.FunctionComponent The component to be wrapped No
Function The function that will be called when the click event occurs outside the component No
RETURN

None

          import { useClickOutside } from "uno-react";
          function App() {
            const [color, setColor] = React.useState("green");
            const onClick = () => setColor("green");
            const toBeEnhanced = () => (
              < div
                className='DemoDiv'
                style=
                onClick={onClick}
              >
                Click me to reset!
              < /div>
            );
            const functionToApply = () => setColor("red");
            const Enhanced = useClickOutside(toBeEnhanced, functionToApply);
            return (
              < div className="App">
                < h1>Uno-React< /h1>
                < h2>useClickOutside< /h2>
                < h3>Click outside component to see magic!< /h3>
                < div
                  style=
                >
                  < Enhanced />
                < /div>
              < /div>
            );
          }
        
Open CodeSandbox

useEffectWithDebounce

This hooks run an effect with a debounce. Each time any input change, it will be registered. when happens the debounce time whitout changes, the effect will be run. (This function does not return anything).

PARAMETERS
Type Description Optional
Function The function that will be run. No
Number Time that have to happend to run the effect. No
Array An array of variables that the effect depends on. No
RETURN

Function, it will be executed once the lapse finishes without interruptions.

          import { useEffectWithDebounce, useStateForField } from "uno-react";
          function App() {
            const [searchText, handleChange, setSearchText] = useStateForField("");
            const debounceTime = 2000;
            const searchUsers = () => console.log(`searching: ${searchText}`);
            useEffectWithDebounce(searchUsers, debounceTime, [searchText]);
            return (
              < div className="App">
                < h1>Uno-React< /h1>
                < h2>useEffectWithDebounce< /h2>
                < h3>Constantly check for changes!< /h3>
                <>
                  < h1>Input: < /h1>
                  < input value={searchText} onChange={handleChange} />
                  < p> Open the console < /p>
                </>
              < /div>
            );
          }
        
Open CodeSandbox

useEffectWithLoading

This hook handles the process of getting a external resource like a fetch or reading a file, and prevent updating the react state if the component is unmounted before the resource is loaded.

PARAMETERS
Type Description Optional
Function The function that will get the data. No
Object Initial value or initial model. No
Array An array of variables that the effect depends on. No
RETURN

Object - The value that is returned by the effect function when the data has been loaded, otherwise the initialValue.

Boolean - A flag that indicates if the data has been fetched or not.

          import { useEffectWithLoading } from "uno-react";
          function getMyData(input) {
            return new Promise<{}>(resolve => {
              setTimeout(() => resolve(input), 5000);
            });
          }
          function App() {
            const myId = "Hey! I'm your data! :D";
            const myDefault = "";
            const inputs = [];
            const [myData, isLoading] = useEffectWithLoading(
              () => getMyData(myId),
              myDefault,
              inputs
            );
            return (
              < div className="App">
                < h1>Uno-React< /h1>
                < h2>useEffectWithLoading< /h2>
                < h3>Wait for your info to load!< /h3>
                < div>
                  {isLoading ? (
                    < div>Loading ...< /div>
                  ) : (
                    < form>
                      < label>
                        < h1>Data loaded< /h1>
                        {myData}
                      < /label>
                    < /form>
                  )}
                < /div>
              < /div>
            );
          }
        
Open CodeSandbox

useNow

This hook keep the current Date object updated. The value will be updated each second.

RETURN

Date - The current date.

          import { useNow } from "uno-react";
          function App() {
            const [now] = useNow();
            return (
              < div className="App">
                < h1>Uno-React< /h1>
                < h2>useNow< /h2>
                < h3>Watch the seconds fly by!< /h3>
                < div>Seconds: {now.getSeconds()}< /div>
              < /div>
            );
          }
        
Open CodeSandbox

usePersistedState

This hook allows us to set and get values from the localStorage.

PARAMETERS
Type Description Optional
String The default value. This value will be added to the localStorage and returned if the key is not found. No
String The key/id to save the value on the localStorage. No
RETURN

String - The current value saved in localStorage. Function - The function to set the value. Note: This function expects an Object as a parameter.

          import { usePersistedState } from "uno-react";
          function App() {
            const key = "exampleToken";
            const defaultValue = "unosquareToken";
            const [token, setToken] = usePersistedState(defaultValue, key);
            const changeValue = () => setToken("1928238475");
            return (
              < div className="App">
                < h1>Uno-React< /h1>
                < h2>usePersistedState< /h2>
                < h3>Change value and watch the console!< /h3>
                < div>
                  < h1>{token}< /h1>
                  < button onClick={changeValue}>Change value< /button>
                < /div>
                < br />
                < div>{`This value is now in your Local Storage: ${localStorage.getItem(
                  key
                )}`}< /div>
              < /div>
            );
          }
        
Open CodeSandbox

useResolutionSwitch

This hook listen to the resize window event and keep the isResolution flag updated.

PARAMETERS
Type Description Optional
Number Size limit (px). defaultValue: 1000 Yes
Number Debounder timeout, the variable will change after this debounder time (ms). defaultValue: 500 Yes
RETURN

boolean - true when window outerSize is smaller than the outerWith passed as a parameter.

          import { useResolutionSwitch } from "uno-react";
          function App() {
            const outerWidth = 1000;
            const timeout = 1000;
            const [size] = useResolutionSwitch(outerWidth, timeout);
            return (
              < div className="App">
                < h1>Uno-React< /h1>
                < h2>useResolutionSwitch< /h2>
                < h3>Resize the window and watch the magic!< /h3>
                < h1>{size ? "mobile" : "desktop"}< /h1>
              < /div>
            );
          }
        
Open CodeSandbox

useStateForField

Similar to useStateForModel this hook helps us to keep the value of a variable that is related to an input, but in this case useStateForField works just with one value.

PARAMETERS
Type Description Optional
Object Initial value or initial model. No
RETURN

Object - The current value, that keeps the information updated. Function - This function should be called on the onChange event. Function - This function helps us to update the value manually.

          import { useStateForField } from "uno-react";
          function App() {
            const [myValue, handleChange, setMyValue] = useStateForField("");
            const reset = () => setMyValue("");
            return (
              < div className="App">
                < h1>Uno-React< /h1>
                < h2>useStateForField< /h2>
                < h3>Enter a new input to see magic!< /h3>
                < div>
                  < h1>{myValue}< /h1>
                  < input value={myValue} onChange={handleChange} />
                  < button onClick={reset}>Reset value< /button>
                < /div>
              < /div>
            );
          }
        
Open CodeSandbox

useStateForModel

This hook allows us to keep updated the values of a model that are related to an input, handling the input's onChange calls. During the first render the model will have the initialValue.

PARAMETERS
Type Description Optional
Object Initial value or initial model. No

Note: The handleChange method will update the model by the target.name event property if it is found, otherwise it will be added to the model. Note: Calling the handleChange method with an object as a param instead of an event, the object will be merged with the current model.

RETURN

Object - The current value, that keeps the information updated. Function - This function should be called on the onChange event.

          import { useStateForModel } from "uno-react";
          function App() {
            const [model, handleChange] = useStateForModel({
              id: 1,
              name: "John",
              lastName: "Doe"
            });
            const changeName = () => handleChange({ name: "John" });
            return (
              < div className="App">
                < h1>Uno-React< /h1>
                < h2>useStateForModel< /h2>
                < h3>Write your name and watch what happens!< /h3>
                < div>
                  < h1>
                    {model.id} - {model.name} - {model.lastName}
                  < /h1>
                  < input name="name" onChange={handleChange} value={model.name} />
                  < input name="lastName" onChange={handleChange} value={model.lastName} />
                  < button onClick={changeName}>Reset Name< /button>
                < /div>
              < /div>
            );
          }
        
Open CodeSandbox

useStateForModelWithLoading

This hook allows us to keep updated the values of a model that are related to an input, handling the input's onChange calls like useStateForModel does, but in additino this hook allows us to load the data from an external resource. This hook is a mix between useStateForModel and useEffectWithLoading, you can use it just as useStateForModel and handle the loading with the extra variable returned isLoading.

PARAMETERS
Type Description Optional
Function the function that will get the data. No
Object Initial value or initial model. No
Array An array of variables that the effect depends on. No
RETURN

Object - The value that is returned by the effect function when the data has been loaded, otherwise the initialValue. Boolean - A flag that indicates if the data has been fetched or not. Function - This function should be called on the onChange event.

          import { useEffectWithDebounce, useStateForField } from "uno-react";
          function App() {
            const [searchText, handleChange, setSearchText] = useStateForField("");
            const debounceTime = 2000; // 2 Seconds
            const searchUsers = () => console.log(`searching: ${searchText}`);
            useEffectWithDebounce(searchUsers, debounceTime, [searchText]);
            return (
              < div className="App">
                < h1>Uno-React< /h1>
                < h2>useEffectWithDebounce< /h2>
                < h3>Constantly check for changes!< /h3>
                <>
                  < h1>Input: < /h1>
                  < input value={searchText} onChange={handleChange} />
                  < p> Open the console < /p>
                </>
              < /div>
            );
          }
        
Open CodeSandbox

useToggle

This hook handles the switch on boolean values. The value will be toggled each time the function toggle is called.

PARAMETERS
Type Description Optional
Boolean Default or initial value. No
RETURN

Boolean - The current value. Function - The function that toggles the value.

          import { useToggle } from "uno-react";
          function App() {
            const defaultValue = false;
            const [myValue, toggle] = useToggle(defaultValue);
            return (
              < div className="App">
                < h1>Uno-React< /h1>
                < h2>useToggle< /h2>
                < h3>Switch on and off!< /h3>
                < div>
                  < h1 style=>
                    {myValue ? "On" : "Off"}
                  < /h1>
                  < button onClick={toggle}>Toggle< /button>
                < /div>
              < /div>
            );
          }
        
Open CodeSandbox

ValidatorForm

This component extends the original ValidatorForm rules. This component works for wrap TextValidator component(s) and for register any other custom rulthis rules can be used in the wrapped components.

Rules:
  • isNotAllBlanks: Validates that the input is not empty, white spaces are ignored.
  • maxNaturalNumber: Validates that the input number si not greather than the given.
  • validateEndDate: Validates than endDate is later than startDate.
  • startDateGreaterThanEndDate: Validates that a date is bigger than other.
  • isImage: Verify that the input correspond to a image name with image file extension.
  • atLeastOneLowerAndUpperCase: Verify that the input has at least one letter in lower case and one in upper case.
  • atLeastOneNumber: Verify that the input has at least one number.
  • atLeastOneSpecialCharacter: Verify that the input has at least one special character (e.g. * # $ &).
  • pincodeValidator: Verify the input contains only numeric values and has a length of 6 characters.
  • password: Validated that the input has at least a length of 8 characteres and contains especial characters, lower case & upper case characters.
  • isPasswordMatch: Verify that the input is equal to another value. (e.g. when validated password & password verfication fields).
          import { useStateForModel, ValidatorForm } from "uno-react";
          function App() {
            const [fields, handleChange] = useStateForModel({
              isNotAllBlanks: ""
            });
            const onSubmit = () => console.log("has submitted");
            return (
              < div className="App">
                < h1>Uno-React< /h1>
                < h2>ValidatorForm< /h2>
                < h3>Make sure you're filling everything right!< /h3>
                < ValidatorForm
                  onSubmit={onSubmit}
                  autoComplete="off"
                  instantValidate={true}
                >
                  < TextValidator
                    id="isNotAllBlanks"
                    name="isNotAllBlanks"
                    value={fields.isNotAllBlanks}
                    onChange={handleChange}
                    validators={["required", "isNotAllBlanks:5"]}
                    errorMessages={[
                      "This field is required",
                      "The minimum length is 5 characters, blank spaces are ignored"
                    ]}
                  />
                < /ValidatorForm>
              < /div>
            );
          }
        
Open CodeSandbox