Redirecting in a Frontastic component

📘

This is an article for advanced users of Frontastic.

Frontastic components not only display information and eye-catching content, but they can also perform advanced functionality a redirect is one of them.

However, be careful as there can be side-effects. For example, having multiple Frontastic components on the same page that uses a redirect at the same time can lead to undetermined behavior.

Let's look at how you could implement a redirect in a Frontastic component with an example.

There are times when a search can result in zero items returned. You could display some helpful information here, or you could redirect your customers to a page with more meaningful content to the search.

To implement a redirect, we can do this in a Frontastic component. Of course, the component needs a schema that will require a data source type of product-list which is the same search data source of the corresponding dynamic page. We can also add a configuration that can select a page folder where the redirect will go to in the Frontastic studio.

Below is the schema you would use for your redirect Frontastic component and then add to the Frontastic studio (see the Creating a Frontastic component in the studio article for more info):

{
    "tasticType": "my-zero-search-results-redirect",
    "name": "Zero search results redirect",
    "schema": [
        {
            "name": "Redirect",
            "fields": [
                {
                    "label": "Products",
                    "field": "stream",
                    "type": "stream",
                    "streamType": "product-list"
                },
                {
                    "label": "Redirect to Node",
                    "field": "redirectNode",
                    "required": true,
                    "type": "node"
                }
            ]
        }
    ]
}

In the Frontastic component code itself (see the Frontastic component article or more info), the data source is then checked for results and if there are zero results returned, the redirect is performed. We use the fact that there's a route for every page folder registered in the Frontastic router to simply perform the redirect.

import React, { useEffect } from 'react';
import { compose } from 'redux';
import tastify from 'frontastic-catwalk/src/js/helper/tastify';
import app from 'frontastic-catwalk/src/js/app/app';

const ZeroSearchResultsRedirect = ({ data }) => {
    useEffect(() => {
        if (data.stream.items.length === 0) {
            app.getRouter().push('node_' + data.redirectNode.nodeId);
        }
    }, []);

    return null;
};

export default compose(tastify())(ZeroSearchResultsRedirect);