React Utils and Hooks

Table of contents

  1. Overview
  2. asset
  3. documentTitle
  4. route


1. Overview Table of Contents

This framework supports the following utilities:

  • api - Perform RESTful API operations. More details in the api page.
  • asset - Similar to php asset helper. Used for rendering images from local storage and S3 buckets.
  • documentTitle - Sets title for document.
  • route - Similar to php route function. Pass name of controller/action along with any props.

Make your own JavaScript utility file:

php console react:util <util_name>

The file gets created at resources\js\utils\.

Hooks are another type of support file. Create your own custom hooks by running the following command:

php console react:hook <hook-name>

New hooks are created at resources\js\hooks\. All hooks start with use but you don’t have to add use when generating a new one.


2. asset Table of Contents

Used to retrieve assets from the project or S3 bucket. Unless the local parameter is set to true it will use S3 bucket specified in .env file.

Parameters:

  • path - Path to the asset
  • local - Reference path withing project directory structure. Default value is false.

Example using local:

<img className="w-50" src={asset("public/logo.png", true)} alt="Framework Logo" />

This retrieves the project logo from the public directory.

Example with S3 bucket:

<img src={asset(profileImage.url)}
    className="img-thumbnail mx-auto my-5 d-block w-50 rounded border border-primary shadow-lg"
    loading="lazy"
/>

Uses S3_BUCKET as host. By default this variable is set to APP_DOMAIN.


3. documentTitle Table of Contents

Sets the document title for current page.

Setup:

import documentTitle from "@chappy/utils/documentTitle"

Usage:

function Edit({user, errors, profileImages}) {
    documentTitle(`Edit Details for ${user.username}`);

    return (
        <>
        ...
        </>
    )
}


4. route Table of Contents

Redirects a user to a view using dot notation.

Parameters:

  • path - The path using dot notation (controller_name.action_name)
  • params - Any parameters you want to pass to controller’s action as an array

Example:

<a href={route('profile.edit', [user.id])} className="btn btn-info btn-sm mx-2 mb-3">
    <i className="fa fa-edit"></i> Edit User Profile
</a>