0

I'm creating custom types for components in TypeScript (with strict null checks enabled) and I want to confirm if it makes sense to be doing null checks on props.fields, eg.:

if (!props.fields) {
  return <></>;
}

A real example would be:

type myCustomProps = ComponentProps & Website.Feature.Main.MyComponent;

Where ComponentProps is the default type that ships with JSS:

export type ComponentProps = {
  rendering: ComponentRendering;
  params: ComponentParams;
};

And where Website.Feature.Main.MyComponent is:

export type MyComponent = {
  id?: string;
  url?: string;
  fields: {
    backgroundImage: ImageField;
  }
}

In this case, I'm specifically referring to a Component Rendering. The interface that ships with JSS does seem to indicate that it's possible for the fields to be null (note the fields?), but when might that be the case?

/**
 * Definition of a component instance within a placeholder on a route
 */
export interface ComponentRendering {
    componentName: string;
    dataSource?: string;
    uid?: string;
    placeholders?: PlaceholdersData;
    fields?: ComponentFields;
    params?: ComponentParams;
}

According to the above, Sitecore seems to be implying that the componentName can never be null, but everything else can be.

Thus far I haven't been able to find any cases in which fields is null, such as when the component is being added to a page or when a datasource is missing.

One obvious example I can think of is if the component has no fields, but in that case, a dev is highly unlikely to reference props.fields because there are none.

2 Answers 2

0

Aside from a component having no fields, one real-world scenario that can be quite likely to occur is if the template fields aren't published, in which case you would want to do a null check on props.fields.

0

Yes, if template is published then field can not be null, but error may occurs when you made typo issue for fieldname or fieldname that is not on template that we use on component.

To handle null check on prop fields, 
You can safely use getFieldValue which you can import from sitecore-jss-react.
Look at this function here
Example:

import { getFieldValue } from '@sitecore-jss/sitecore-jss-react';

const props = {
  "fields": {
    "heading": {
      "value": ""
    },
    "sample": {
      "value": "111."
    },
    "sample2": {
      "value": "222."
    }
  }
}

const headingValue = getFieldValue(props.fields, 'heading', null);

const component = headingValue ? <RichText field={fields.heading} /> : null;
1
  • This appears to be JS; not TS. Commented Feb 18, 2023 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.