react-admin: handle null on ReferenceFields

Viewed 2202

I have a ReferenceField as follows:

<ReferenceField label="User" source="user_id" reference="users">
    <TextField source="name" />
</ReferenceField>

It works nice but the problem is sometimes user_id might be null and that causes the loading bar to be displayed indefinetely. Is there any way that if the value of the reference field is null to display an alternative text or similar?

2 Answers

No, there is no alternative text or something as an option.
Your id being null, should just leave the ReferenceField empty, not displaying loading bar.


Changing your ReferenceField element by adding "allowEmpty" and it should work: <ReferenceField label="User" source="user_id" reference="users" allowEmpty>

Just want to mention here that it seems to me the allowEmpty prop has been removed from the ReferenceField component for newer versions, so the proposed solution did not work for me. I simply created a custom component NullableReferenceField to prevent anything from being rendered (and even an API request from being issued) whenever source is null. You may of course also customize what's being displayed in that case.

import React from "react";
import {
  ReferenceField,
  useRecordContext,
} from "react-admin";

export default function NullableReferenceField({ source, ...props }) {
  const record = useRecordContext();
  if (!record[source]) {
    return null;
  }
  return <ReferenceField source={source} {...rest} />;
}
Related