Robert Strauch
Robert Strauch

Reputation: 12896

Defining a reusable template for views in react-admin

Using react-admin I have an EditView like this:

export const LanguageEdit = props => (
  <Edit title="Edit: Language" {...props}>
    <SimpleForm>
      <TextInput source="name" label="Name" />
      <TextInput source="iso1" label="ISO-1" />
      <TextInput source="iso2" label="ISO-2" />
    </SimpleForm>
  </Edit>
);

My application will have several of these edit views, each with a different content in the <SimpleForm> element. The title however will differ only slightly in the different views.

<Edit title="Edit: Language" {...props}>
<Edit title="Edit: City" {...props}>
<Edit title="Edit: Country" {...props}>

Is there some way to define this as a "template" which will then be used in all the edit views?

Template

<Edit title="Edit: ${currentViewName}" {...props}>
  <SimpleForm>
    ${somePlaceholder}
  </SimpleForm>
</Edit>

View content (pseudo code)

currentViewName = "Country";
somePlaceholder => (
          <TextInput source="name" label="Name" />
          <TextInput source="iso1" label="ISO-1" />
          <TextInput source="iso2" label="ISO-2" />
);
applyTemplate(currentViewName, somePlaceholder);

Upvotes: 1

Views: 128

Answers (1)

Kmaschta
Kmaschta

Reputation: 2429

You can wrap the Edit component like:

const EditTemplate = ({ title, children, ...props }) => (
    <Edit title={`Edit: ${title}`} {...props}>
        <SimpleForm>
            {children}
        </SimpleForm>
    </Edit>
)

And use it as a normal Edit view:

export const LanguageEdit = props => (
  <EditTemplate title="Language" {...props}>
      <TextInput source="name" label="Name" />
      <TextInput source="iso1" label="ISO-1" />
      <TextInput source="iso2" label="ISO-2" />
  </EditTemplate>
);

Upvotes: 3

Related Questions