Sometimes we may need to use Component GraphQL Query – we might read data from datasource or context item.
For example, we need to create a Publish date component that will get the data from the datasource but if there is no datasource it will read the data from context item. We created a rendering component “PublishDate” and following is the component GraphQL Query:
query TitleQuery($datasource: String!, $contextItem: String!, $language: String!) {
datasource: item(path: $datasource, language: $language) {
url {
path
siteName
}
field (name: "PublishDate"){
jsonValue
}
}
contextItem: item(path: $contextItem, language: $language) {
url {
path
siteName
}
field (name: "PublishDate"){
jsonValue
}
}
}
.
We can create a template for Publish Date and a datasource from the template:
JSS component will receive both datasource and context item values. It looks like
import {
DateField
} from '@sitecore-jss/sitecore-jss-nextjs';
interface PublishDateFields {
data: {
datasource: {
url: {
path: string;
siteName: string;
};
field: {
jsonValue: {
value: string;
editable: string;
};
};
};
contextItem: {
url: {
path: string;
siteName: string;
};
field: {
jsonValue: {
value: string;
editable: string;
};
};
};
};
}
interface SitecoreField {
value: string;
type: string; // This can be a Sitecore-specific type identifier
}
function convertToSitecoreField(value: string): SitecoreField {
return {
value,
type: "Date",
};
}
type PublishDateProps = {
params: { [key: string]: string };
fields: PublishDateFields;
};
const PublishDate = (props: PublishDateProps): JSX.Element => {
const datasource = props.fields?.data?.datasource || props.fields?.data?.contextItem;
const publishDate = convertToSitecoreField(datasource?.field?.jsonValue?.value);
return (
<div>
{'Published on '}
<DateField
field={publishDate}
render={(date: Date) => date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) }
editable={true}
/>
</div>
);
};
export default PublishDate;
.
In the experience editor it looks like