Skip to content

Instantly share code, notes, and snippets.

@cwparsons
Last active March 19, 2019 17:14
Show Gist options
  • Save cwparsons/3263896982ba5895e234528dc6785e5e to your computer and use it in GitHub Desktop.
Save cwparsons/3263896982ba5895e234528dc6785e5e to your computer and use it in GitHub Desktop.
Using React
<div data-react-component="CustomReactComponent"
data-prop-api-url="/api/service"
data-prop-data="{ items: [ ... ] }"
data-prop-has-load-more-button="true"
data-prop-no-results-label="No results..."
data-prop-page-limit="10"
/>
interface ICustomReactComponentProps {
apiUrl: string;
data: object;
hasLoadMoreButton: boolean;
noResultsLabel: string;
pageLimit: number;
}
/**
* Loop through all data attributes on the root element and use data-prop-* as props.
*/
export default (element: Element) => {
const props = {};
if (element instanceof HTMLElement) {
const dataset = element.dataset;
for (const attribute in dataset) {
if (attribute.indexOf('prop') === 0) {
let key = attribute.replace(/^prop/, '');
key = key.charAt(0).toLowerCase() + key.slice(1);
const value = dataset[attribute];
if (value && !isNaN(Number(value))) {
// If prop is a number
props[key] = parseInt(value, 10);
} else if (value && value.toLowerCase() === 'true') {
props[key] = true;
} else if (value && value.toLowerCase() === 'false') {
props[key] = false;
} else if (value && isJson(value)) {
// Prop is an object
props[key] = JSON.parse(value);
} else {
// Prop is a string
props[key] = value;
}
}
}
}
return props;
};
function isJson(value: string) {
try {
JSON.parse(value);
} catch (e) {
return false;
}
return true;
}
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import CustomReactComponent, { ICustomReactComponentProps } from './custom-react-component';
import forEach from '../utilities/forEach';
import getPropsFromAttributes from '../utilities/getPropsFromAttributes';
const SELECTOR = '[data-react-component="CustomReactComponent"]';
const elements = document.querySelectorAll(SELECTOR);
forEach(elements, (element) => {
const props = getPropsFromAttributes(element) as ICustomReactComponentProps;
ReactDOM.render(<CustomReactComponent {...props} />, element);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment