Extending result item component

📘

Prerequisite

Create results widget

Setup for development with typescript

Steps to extend

  1. Create a components directory in the designated react folder.
  2. Create a React component file (e.g. CustomItem.tsx)
  3. Open the file to edit and import React and ResultItemProps
import React from 'react';  
import { ResultItemProps } from 'react-hawksearch';
  1. Create the component function
function CustomItem({ item }: ResultItemProps) {  
  // Configuration goes here  
}
  1. For the configuration, declare all the fields that are gone be used in this component
let title = item.getDocumentValue('title');  
let content = item.getDocumentValue('content');
  1. The component function should return the structure
return (  
	<div>  
		<h3>{title}</h3>  
		<p>{content}</p>  
	</div>  
)
  1. Export the component
export default CustomItem;
  1. Save the file.
  2. Open the results component file for editing.
  3. Import the newly created item component
import CustomItem from '../components/CustomItem';
  1. Locate the Results component initialization. It should be in the App structure.
function App() {  
    return (  
    ...  
      <Results />  
    ...  
    );  
}

12, Set the ResultItem prop to point to the item component

function App() {  
    return (  
    ...  
      <Results ResultItem={CustomItem} />  
    ...  
    );  
}
  1. Save and re-build the JS resources.

Example

Creating a custom item for dynamic layout based on content type (e.g. components/ContentTypeDynamicItem.tsx)

import React from 'react';
import { ResultItemProps } from 'react-hawksearch';

function ContentTypeDynamicItem({ item }: ResultItemProps) {
    var contentType = item.getDocumentValue('contenttype');
    var title = item.getDocumentValue('title');
    var link = item.getDocumentValue('link');
    var summary = item.getDocumentValue('summary');
    var content = item.getDocumentValue('content');
    var image = item.getDocumentValue('image');
    var item;

    switch (contentType) {
        case "Telerik.Sitefinity.Events.Model.Event":
            item =
                <div>
                    <div><h3>{title}</h3></div>
                    <div><img src={image} /></div>
                    <div>{content}</div>
                </div>
            break;

        case "Telerik.Sitefinity.News.Model.NewsItem":
            item =
                <div>
                    <div><h3>{title}</h3></div>
                    <div>{summary}</div>
                    <p><a href={link}>Read more</a></p>
                </div>
            break;

        default:
            item =
                <div>
                    <div><h3>{title}</h3></div>
                    <div>{content}</div>
                </div>
            break;
    }

    return (
        <div>
            {item}
        </div>
    );
}

export default ContentTypeDynamicItem;