Skip to content

Instantly share code, notes, and snippets.

@kevinweber
Last active February 12, 2018 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinweber/7af8e310fa2d0ae1ce5199d3ed8566a2 to your computer and use it in GitHub Desktop.
Save kevinweber/7af8e310fa2d0ae1ce5199d3ed8566a2 to your computer and use it in GitHub Desktop.
AEM-React / AEM-Preact integration
import './index.scss';
import {
isObject,
traverseObjectByPath,
} from 'utils/methods';
import {
// INFO: The 'h' function import gets used in the final, transpiled code as a drop in replacement for React.createElement, and so needs to be imported even if you don't explicitly use it in the code you write
// eslint-disable-next-line no-unused-vars
h,
render,
Component as ReactComponent,
} from 'preact';
import {
DataStore,
} from 'aem/aem-data-store';
import AEM from 'aem';
class List extends ReactComponent {
constructor() {
super();
this.setState({
data: {
template: DataStore.get('template'),
},
});
}
componentDidMount() {
/**
* THIS IS A DEMO illustrating how we can subscribe to changes
* `DataStore.subscribe(callback)`
*
* Whenever an update of the storage is triggered as follows...
* `DataStore.update('template', '', newData)`
*
* ...the callback we added while subscribing gets triggered.
* Uncommend the `setInterval` below to see an exemplary update.
*/
DataStore.subscribe(() => {
this.setState({
data: {
template: DataStore.get('template'),
},
});
});
// setInterval(() => {
// const testUpdate = {
// 'aem': {
// 'config': {
// 'exterior': {
// 'prop1': 'Updates work 2: ' + Math.random().toFixed(7),
// 'prop2': 'Testing...',
// 'prop3': {
// 'child1': 'That works.',
// 'child2': 'YEAH!'
// }
// }
// }
// }
// };
// DataStore.update('template', '', testUpdate);
// }, 1000);
}
render(props, state) {
const data = props.dataRecursive || traverseObjectByPath(state.data.template, props.aemComponent.path);
const items = [];
for (const property in data) {
const value = data[property];
if (isObject(value)) {
items.push(<List dataRecursive={value} />);
} else {
items.push(<ListItem text={value} />);
}
}
return (
<ul>{items}</ul>
);
}
}
class ListItem extends ReactComponent {
render(props) {
return (
<li>{props.text}</li>
);
}
}
class Tree extends AEM.Component {
init() {
this.path = this.element.querySelector('[data-aem-component]').dataset.path;
this.listRoot = this.element.querySelector('[data-react-root]');
render(<List aemComponent={this} />, this.listRoot);
}
}
AEM.registerComponent('.section-data-tree', Tree);
<div data-aem-component
data-sly-test="${properties.dataPath}"
data-path="${properties.dataPath}">
<div data-react-root></div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment