Skip to content

Instantly share code, notes, and snippets.

@danielpowell4
Last active January 27, 2023 10:17
Show Gist options
  • Save danielpowell4/fda80fe497486ecb41924461a81485ae to your computer and use it in GitHub Desktop.
Save danielpowell4/fda80fe497486ecb41924461a81485ae to your computer and use it in GitHub Desktop.
a simple way to hand off server side rendered data attributes to props in components
// - example rails erb view
// <div id="edit-react-form"
// data-submit-endpoint="<%= billing_profile_path(@billing_profile.token) %>"
// data-initial-values="<%= @form.initial_values.to_json %>"
// data-cancel-url="<%= billing_profile_path(@billing_profile.token) %>"
// >
// </div>
function parsePropsFromDataset(dataset) {
let stringifyedOptions = { ...dataset }; // convert DOMStringMap into Object
let props = {};
for (let key of Object.keys(stringifyedOptions)) {
let rawValue = stringifyedOptions[key];
try {
props[key] = JSON.parse(rawValue);
} catch {
props[key] = rawValue; // for { typeAndId: "Student:1232" }
}
}
return props;
}
// example usage in React
import * as React from "react";
import { render } from "react-dom";
import { parsePropsFromDataset } from "../lib";
import App from "../app";
document.addEventListener("DOMContentLoaded", () => {
const el = document.getElementById("app");
if (!el) return;
const initialState = el.dataset
? parsePropsFromDataset(el.dataset).initialState
: {};
render(<App initialState={initialState} />, el);
});
<!-- via rails content_for -->
<div id="app" <% if content_for(:initial_state).present? %>
data-initial-state="<%= content_for(:initial_state) %>"
<% end %>>
<!-- see react land -->
</div>
<!-- via simple controller vars w/ route helpers -->
<div id="edit-react-form"
data-submit-endpoint="<%= billing_profile_path(@billing_profile.token) %>"
data-initial-values="<%= @form.initial_values.to_json %>"
data-cancel-url="<%= billing_profile_path(@billing_profile.token) %>"
>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment