Search code examples
reactjstypescriptreact-admin

React-admin Edit title missing record with typescript


In order to use Typescript feature under react-admin, I followed this official example to type the Edit title:

interface UserTitleProps {
  record: UserRecord;
}
const UserTitle: FC<UserTitleProps> = ({ record }) => {
  const identifier = record?.email || record?.phoneNumber;

  if (record?.name) {
    return `${record?.name} (${identifier})`;
  }

  return identifier;
};
export const UserEdit: FC<EditProps> = (props) => (
  <Edit
    title={<UserTitle />}
    {...props}
  >
    <UserForm />
  </Edit>
);

But the code above gave me the following typescript error:

Property 'record' is missing in type '{}' but required in type 'UserTitleProps'.  TS2741

    103 | export const UserEdit: FC<EditProps> = (props) => (
    104 |   <Edit
  > 105 |     title={<UserTitle />}
        |             ^
    106 |     {...props}
    107 |   >
    108 |     <UserForm />

Indeed, the record props is not really passed but according to the documentation and the following sample, there is nothing to add.

Am I missing something?

Thanks


Solution

  • If you scrutinized this critically:

    interface UserTitleProps {
      record?: UserRecord; // make this an optional property
    }
    

    You'll notice that record is an optional property but in your code it's mandatory.
    Therefore for your case, you'll need to pass the record prop.

    But if you update that line, to make the prop optional, then TypeScript should stop complaining unless otherwise.


    From their page-title documentation

    React-admin says that when you pass an element as title, it's cloned.
    And from within <EditView>, the current record is injected to the title.

    Therefore, you never have to pass the record prop explicitly.
    And thus record should always be an "optional" prop when added to the interface since you never have to pass it directly.

    In this video, you can see what's happening underneath in case you're interested in the details.

    export const UserEdit: FC<EditProps> = (props) => {
    
      return (
        <Edit
          title={<UserTitle />} // "record" prop is never passed explicitly
          {...props}
        >
          <UserForm />
        </Edit>
      );
    };