Skip to content

Instantly share code, notes, and snippets.

@erzr
Last active December 1, 2019 01:54
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 erzr/60fa7ccb42002b4196507485edc9d33d to your computer and use it in GitHub Desktop.
Save erzr/60fa7ccb42002b4196507485edc9d33d to your computer and use it in GitHub Desktop.
ClientSidePlaceholder for Sitecore JSS
import React from 'react';
import { withSitecoreContext, dataApi, Placeholder } from '@sitecore-jss/sitecore-jss-react';
import { dataFetcher } from './dataFetcher';
import config from './temp/config';
class ClientSidePlaceholder extends React.Component {
constructor(props) {
super(props);
this.state = {
elements: null
};
}
fetchPlaceholder(placeholderName, itemLanguage, itemId) {
return dataApi.fetchPlaceholderData(placeholderName, itemId, {
layoutServiceConfig: { host: config.sitecoreApiHost },
querystringParams: { sc_lang: itemLanguage, sc_apikey: config.sitecoreApiKey },
fetcher: dataFetcher,
});
}
componentDidMount() {
const shouldFetch = this.shouldFetchPlaceholder();
if (shouldFetch) {
const placeholderName = this.props.name;
const { route } = this.props.sitecoreContext;
const { itemLanguage, itemId } = route;
this.fetchPlaceholder(placeholderName, itemLanguage, itemId)
.then(result => {
this.setState({
elements: result.elements
});
})
}
}
render() {
const rendering = {
...this.props.rendering
};
rendering.placeholders[this.props.name] = this.state.elements ? this.state.elements :
this.props.hideInitialContents ? [] : rendering.placeholders[this.props.name];
const placeholderProps = {
...this.props,
rendering
}
return <Placeholder {...placeholderProps} />
}
isClientside() {
return typeof window !== 'undefined';
}
isDisconnectedMode() {
const disconnectedMode = this.props.sitecoreContext.site.name === 'JssDisconnectedLayoutService';
return disconnectedMode;
}
isPageEditing() {
const isEditing = this.props.sitecoreContext.pageEditing;
return isEditing;
}
shouldFetchPlaceholder() {
return this.isClientside() && !this.isDisconnectedMode() && !this.isPageEditing();
}
}
export default withSitecoreContext()(ClientSidePlaceholder);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment