Skip to content

Instantly share code, notes, and snippets.

@jahirfiquitiva
Last active November 20, 2021 04:35
Show Gist options
  • Save jahirfiquitiva/51883474cbd514f4d1426d070b582a09 to your computer and use it in GitHub Desktop.
Save jahirfiquitiva/51883474cbd514f4d1426d070b582a09 to your computer and use it in GitHub Desktop.
React component that supports multiple types

Objective

Build a React component that support rendering different types of content. Depending on the content type, a slightly different layout will be shown.

Content types:

  • Website
  • Blog
  • Project

Expected results:

  • Given a contentType, the content field should be of the corresponding type.
  • Back link should be shown if backText and backHref are defined
  • Title should be name field for content type Project, or title field otherwise
  • Other fields should be shown if available and defined.
interface CommonProps {
backText?: string;
backHref?: string;
}
interface WebsiteContent {
contentType: 'website';
content: Website;
}
interface BlogContent {
contentType: 'blog';
content: Blog;
}
interface ProjectContent {
contentType: 'project';
content: Project;
}
type ContentProps = CommonProps & (WebsiteContent | BlogContent | ProjectContent);
export const Content = (props: ContentProps) => {
const { backText, backHref, contentType, content, children } = props;
return <div>
{backText && backHref && <a href={backHref}>{backText}</a>}
<h1>{content.title || content.name}</h1>
{content.subtitle && <p>{content.subtitle}</p>}
{content.date && <p>{content.date}</p>}
{content.excerpt && <p>{content.excerpt}</p>}
{children}
</div>
};
interface CommonFields {
slug: string;
}
interface Website extends CommonFields {
title: string;
subtitle?: string;
}
interface Blog extends CommonFields {
title: string;
excerpt?: string;
date?: string;
}
interface Project extends CommonFields {
name: string;
link?: string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment