Skip to content

Latest commit

 

History

History
104 lines (87 loc) · 4.75 KB

File metadata and controls

104 lines (87 loc) · 4.75 KB

ReactOnRails JavaScript API

CSRF protection

Rails has built-in protection for Cross-Site Request Forgery (CSRF), see Rails Documentation. To nicely utilize this feature in JavaScript requests, React on Rails provides two helpers that can be used as following for POST, PUT or DELETE requests:

import ReactOnRails from 'react-on-rails';

// reads from DOM csrf token generated by Rails in <%= csrf_meta_tags %>
csrfToken = ReactOnRails.authenticityToken();

// compose Rails specific request header as following { X-CSRF-Token: csrfToken, X-Requested-With: XMLHttpRequest }
header = ReactOnRails.authenticityHeaders(otherHeader);

If you are using jquery-ujs for AJAX calls, then these helpers are not needed because the jquery-ujs library updates header automatically, see jquery-ujs documentation.

API

The best source of docs is the interface ReactOnRails in types/index.ts. Here's a quick summary. No guarantees that this won't be outdated!

/**
 * Main entry point to using the react-on-rails NPM package. This is how Rails will be able to
 * find your components for rendering.
 *
 * Component detection: React on Rails distinguishes between component types by parameter count:
 * - 0-1 params: Regular React component (function or class)
 * - 2 params, or any function with `.renderFunction = true`: Render-Function — called with (props, railsContext),
 *   returns a React component, `{ renderedHtml }` object, or Promise (Pro Node renderer only)
 * - 3 params: Renderer function — called with (props, railsContext, domNodeId),
 *   responsible for calling ReactDOM.render/hydrate directly (client-only)
 *
 * Render-Functions can return:
 * - A React component (function or class) — used with `react_component`
 * - `{ renderedHtml: string }` — raw HTML string, used with `react_component`
 * - `{ renderedHtml: ReactElement }` — server rendering only, used with `react_component`
 * - `{ renderedHtml: { componentHtml, ...otherKeys } }` — used with `react_component_hash`
 * - `{ renderedHtml, clientProps }` — clientProps are merged into client hydration props
 * - `{ redirectLocation, routeError }` — legacy (React Router v3/v4), see render-functions docs
 *
 * @param components (key is component name, value is component)
 */
register(components);

/**
 * Allows registration of store generators to be used by multiple React components on one Rails
 * view. Store generators are functions that take one arg, props, and return a store. Note that
 * the setStore API is different in that it's the actual store hydrated with props.
 * @param stores (key is store name, value is the store generator)
 */
registerStoreGenerators(storesGenerators);

/**
 * Allows retrieval of the store by name. This store will be hydrated by any Rails form props.
 * Pass optional param throwIfMissing = false if you want to use this call to get back null if the
 * store with name is not registered.
 * @param name
 * @param throwIfMissing Defaults to true. Set to false to have this call return undefined if
 *        there is no store with the given name.
 * @returns Redux Store, possibly hydrated
 */
getStore(name, (throwIfMissing = true));

/**
 * Renders or hydrates the React element passed. In case React version is >=18 will use the root API.
 * @param domNode
 * @param reactElement
 * @param hydrate if true will perform hydration, if false will render
 * @returns {Root|ReactComponent|ReactElement|null}
 */
reactHydrateOrRender(domNode, reactElement, hydrate);

/**
 * Set options for ReactOnRails, typically before you call ReactOnRails.register
 * Available Options:
 * `traceTurbolinks: true|false Gives you debugging messages on Turbolinks events
 */
setOptions(options);

/**
 * Allow directly calling the page loaded script in case the default events that trigger React
 * rendering are not sufficient, such as when loading JavaScript asynchronously with TurboLinks:
 * More details can be found here:
 * https://reactonrails.com/docs/building-features/turbolinks
 */
reactOnRailsPageLoaded();

/**
 * Returns CSRF authenticity token inserted by Rails csrf_meta_tags
 * @returns String or null
 */
authenticityToken();

/**
 * Returns header with csrf authenticity token and XMLHttpRequest
 * @param {*} other headers
 * @returns {*} header
 */
authenticityHeaders((otherHeaders = {}));

For TanStack Router integration utilities, see react-on-rails-pro/tanstack-router (requires React on Rails Pro).