13. Customizing Volto Components – Mastering Plone 6 development

13. Customizing Volto Components#

Frontend chapter

Get the code: collective/volto-ploneconf

git checkout overrides

More info in The code for the training

In this part you will:

Customize existing components and views

Topics covered:

  • Component shadowing

  • Content type view

13.1. Component shadowing#

We use a technique called component shadowing to override an existing Volto component with our local custom version, without having to modify Volto's source code at all. You have to place the replacing file in the same folder path inside the /src/customizations/ folder of your app as the original file in /omelette/src/.

Every time you add a file to your app, you have to restart Volto for changes taking effect. From that point on, the hot module reloading should kick in and reload the page automatically on changes.

You can customize any module in Volto, including actions and reducers, not only components.

The Volto code can be found in /omelette/.

13.3. The news item view#

We want to show the date a News Item is published. This way visitors can see at a glance if they are looking at current news. This information is not shown by default. So you need to customize the way a News Item is rendered.

A News Item has date attributes. The attributes of a content type instance are defined by the schema of a content type and possible behaviors. We had a look at schemas in Content types I and Content types II: Talk. Behaviors are being described in Behaviors. These date attributes are available when the content is fetched by the frontend. But let's first have a look how these attributes are used in a Volto component.

The Volto view component to render a News Item is in /omelette/src/components/theme/View/NewsItemView.jsx.

 1/**
 2 * NewsItemView view component.
 3 * @module components/theme/View/NewsItemView
 4 */
 5
 6import React from 'react';
 7import PropTypes from 'prop-types';
 8import { Container, Image } from 'semantic-ui-react';
 9import {
10  hasBlocksData,
11  flattenToAppURL,
12  flattenHTMLToAppURL,
13} from '@plone/volto/helpers';
14import RenderBlocks from '@plone/volto/components/theme/View/RenderBlocks';
15
16/**
17 * NewsItemView view component class.
18 * @function NewsItemView
19 * @params {object} content Content object.
20 * @returns {string} Markup of the component.
21 */
22const NewsItemView = ({ content }) =>
23  hasBlocksData(content) ? (
24    <div id="page-document" className="ui container viewwrapper event-view">
25      <RenderBlocks content={content} />
26    </div>
27  ) : (
28    <Container className="view-wrapper">
29      {content.title && (
30        <h1 className="documentFirstHeading">
31          {content.title}
32          {content.subtitle && ` - ${content.subtitle}`}
33        </h1>
34      )}
35      {content.description && (
36        <p className="documentDescription">{content.description}</p>
37      )}
38      {content.image && (
39        <Image
40          className="documentImage"
41          alt={content.title}
42          title={content.title}
43          src={
44            content.image['content-type'] === 'image/svg+xml'
45              ? flattenToAppURL(content.image.download)
46              : flattenToAppURL(content.image.scales.mini.download)
47          }
48          floated="right"
49        />
50      )}
51      {content.text && (
52        <div
53          dangerouslySetInnerHTML={{
54            __html: flattenHTMLToAppURL(content.text.data),
55          }}
56        />
57      )}
58    </Container>
59  );
60
61/**
62 * Property types.
63 * @property {Object} propTypes Property types.
64 * @static
65 */
66NewsItemView.propTypes = {
67  content: PropTypes.shape({
68    title: PropTypes.string,
69    description: PropTypes.string,
70    text: PropTypes.shape({
71      data: PropTypes.string,
72    }),
73  }).isRequired,
74};
75
76export default NewsItemView;

Note

  • content is passed to NewsItemView and represents the content item as it is serialized by the REST API. The content data has been fetched by an action on navigating to route http://localhost:3000/my-news-item.

  • The view displays various attributes of the News Item using content.title, content.description or content.text.data.

  • You can inspect all data hold by content using the React Developer Tools for Firefox or Chrome:

../_images/volto_react_devtools.png

Copy this file from /omelette/src/components/theme/View/NewsItemView.jsx to src/customizations/components/theme/View/NewsItemView.jsx.

After restarting Volto, the new file is used when displaying a News Item. To make sure your file is taken into effect, add a small change before the blocks <RenderBlocks content={content} />. If it shows up you're good to go.

Tip

In you own projects you should always do a commit of the unchanged file and another commit after you changed the file. This way you will have a commit in your git history with the change you made. You will thank yourself later for that clean diff!

To display the date add the following before the text:

<p>{content.created}</p>

This will render something like 2022-10-02T21:58:54. Not very user friendly. Let's use one of many helpers available in Volto.

Import the component FormattedDate from @plone/volto/components at the top of the file and use it to format the date in a human readable format.

 1/**
 2 * NewsItemView view component.
 3 * @module components/theme/View/NewsItemView
 4 */
 5
 6import React from 'react';
 7import PropTypes from 'prop-types';
 8import { Container, Image } from 'semantic-ui-react';
 9import {
10  hasBlocksData,
11  flattenToAppURL,
12  flattenHTMLToAppURL,
13} from '@plone/volto/helpers';
14import { FormattedDate } from '@plone/volto/components';
15import RenderBlocks from '@plone/volto/components/theme/View/RenderBlocks';
16
17/**
18 * NewsItemView view component class.
19 * @function NewsItemView
20 * @params {object} content Content object.
21 * @returns {string} Markup of the component.
22 */
23const NewsItemView = ({ content }) =>
24  hasBlocksData(content) ? (
25    <div id="page-document" className="ui container viewwrapper event-view">
26      <p>
27        <FormattedDate date={content.created} includeTime />
28      </p>
29      <RenderBlocks content={content} />
30    </div>
31  ) : (
32    <Container className="view-wrapper">
33      {content.title && (
34        <h1 className="documentFirstHeading">
35          {content.title}
36          {content.subtitle && ` - ${content.subtitle}`}
37        </h1>
38      )}
39      {content.description && (
40        <p className="documentDescription">{content.description}</p>
41      )}
42      {content.image && (
43        <Image
44          className="documentImage"
45          alt={content.title}
46          title={content.title}
47          src={
48            content.image['content-type'] === 'image/svg+xml'
49              ? flattenToAppURL(content.image.download)
50              : flattenToAppURL(content.image.scales.mini.download)
51          }
52          floated="right"
53        />
54      )}
55      {content.text && (
56        <div
57          dangerouslySetInnerHTML={{
58            __html: flattenHTMLToAppURL(content.text.data),
59          }}
60        />
61      )}
62    </Container>
63  );
64
65/**
66 * Property types.
67 * @property {Object} propTypes Property types.
68 * @static
69 */
70NewsItemView.propTypes = {
71  content: PropTypes.shape({
72    title: PropTypes.string,
73    description: PropTypes.string,
74    text: PropTypes.shape({
75      data: PropTypes.string,
76    }),
77  }).isRequired,
78};
79
80export default NewsItemView;

The result should look like this:

A News Item with publishing date.

Now another issue appears. There are various dates associated with any content object:

  • The date the item is created: content.created

  • The date the item is last modified content.modified

  • The date the item is published content.effective

In fact you most likely want to show the date when the item has been published. But while the item is not yet published, that value is not yet set and you will get an error. So we'll add some simple logic to show the effective date only if it exists.

{content.review_state === 'published' && content.effective && (
  <p>
    <FormattedDate date={content.effective} includeTime />
  </p>
)}

As we are in the HTML part of our React component, we surround the JavaScript code with curly braces. Inside Javascript we embrace html in rounded braces.

13.4. Summary#

  • Component shadowing allows you to modify and extend views and other components in Volto.

  • It is a powerful mechanism making changes without the need of complex configuration or maintaining a fork of the code.

  • You need to restart Volto when you add a new overriding.

See also

Volto Hands-On training: Header component