- Notifications
You must be signed in to change notification settings - Fork74
Sample React SPA utilizing the Kontent.ai Delivery API to fetch content.
License
kontent-ai/sample-app-react
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Warning
Deprecation Notice: This repository is no longer maintained.
We encourage you to explore our latest solutions for React integration. Check out theKickstart Sample App or theNext.js Sample App for up-to-date implementations.
Important
This sample app relies on the Dancing Goat project, which is no longer available for creation in Kontent.ai.
If you still wish to use this project, you can import the Dancing Goat project using theData Ops tool by following the instructions provided in ourDancing Goat repository.
This is a sample website written in Typescript utilizing the Kontent.ai Delivery API to retrieve content from Kontent.ai. You can register your developer account athttps://app.kontent.ai. For a brief walkthrough, check outRunning the React sample app at Kontent.ai Learn.
- Install the latest version of NodeJS and npm. You can download both athttps://nodejs.org/en/download/.
- Clone the sample application repository.
- Navigate to the root folder of the application in the command line.
- Type
npm install
to install required npm packages. - Type
npm start
to start a development server. - The application opens in your browser athttp://localhost:3000.
At the first run of the app, you'll be presented with a configuration page. It will allow you to connect the app to your Kontent.ai project or create a new one. You'll also be able to start a trial and convert to a free plan when the trial expires.
Alternatively, you can connect your project manually as per the chapter below.
If you want to change the source Kontent.ai project, follow these steps:
- In Kontent.ai, choose Project settings from the app menu.
- Under Development, choose API keys.
- Copy your Environemnt ID.
- Open
.env.example
in the root directory. - Replace
your_environment_id
with your Environment ID and removeREACT_APP_PREVIEW_API_KEY
entry. - Save and rename the file
.env
.
When you now run the sample application, the application retrieves content from your project.
Deploy, explore and change the app directly in the browser.
If you already have a Kontent.ai account and you want to connect the sample application to a project of your own, you need to provide your Environment ID and your Preview API key to authorize requests to the Delivery Preview API. For example, you can connect the application to your modified version of the sample project.
To preview content in the sample application, follow these steps:
- In Kontent.ai, choose Project settings from the app menu.
- Under Development, choose API keys.
- Copy your Environemnt ID and Preview API key.
- Open
.env.example
in the root directory . - Replace
your_environment_id
andyour_api_key
with your Environment ID and Preview API key. - Save and rename the file
.env
.
When you now run the application, you will see all project content including the unpublished version of content items.
- Navigate tohttps://app.kontent.ai in your browser.
- Sign in with your credentials.
- Manage content in the content administration interface of your sample project.
You can learn more about content editing in our tutorials atKontent.ai Learn.
You can retrieve content either through the Kontent.ai Delivery SDKs or the Kontent.ai Delivery API:
- For published content, use
https://deliver.kontent.ai/ENVIRONMENT_ID/items
. - For unpublished content, use
https://preview-deliver.kontent.ai/ENVIRONMENT_ID/items
.
For more info about the API, see theAPI reference.
You can find the Delivery and other SDKs athttps://github.com/kontent-ai.
This application is based on theCreate React App using the following template--template typescript
.
There are two types of model mapping in this application:
Content type definitions are being generated from content types viaKontent.ai model generator tool. All generated types can be found insrc/Models
folder. The_project.ts
contains information about the project structure such as project languages as well as other structure information like codenames about content types.
Some models displayed in views might require an adjustment from content types. For example, theCafe
content type contains fields forcity
andstreet
and we would like to have a model containing an address in the formatcity, street
. An example of such a view model is inCafeModel.tsx
that can be found in thesrc/ViewModels
folder. To convertCafe
intoCafeModel
the function located insrc/Utilities/CafeListing.ts
can be used.
This solution fetches data using theDelivery client. For more implementation detail to set up the client seesrc/Client.ts
. The data are fetched and stored in acontainer
component directly in its state. Then they are passed to thepresentation
component. For a better understanding see the code example below. However, depending on your needs, you can use other technologies for managing application states such as:
constComponent:React.FC=()=>{const[data,setData]=useState<GeneratedDTO[]>([]);useEffect(()=>{constquery=Client.items<GeneratedDTO>().type(projectModel.contentTypes.generatedDTO.codename)...query.ToPromise().then(data=>setData(data.items));},[]);return({data.map(item=><DisplayItemdto={item}/>)}); ...}
Filters in Kontent.ai are implemented using taxonomies. Filtering examples can be found insrc/Components/BrewerStoreContainer.tsx
orsrc/Components/CoffeeStoreContainer.tsx
. Firstly, the taxonomies groups that contain possible values for filters are loaded inuseEffect
blocks. Selected values for filtering are stored in thefilter
variable. Items to be displayed are then selected with the functionalfilter
function checking whether the item matches the filter.
interfaceFilterType{[index:string]:string[];processings:string[];productStatuses:string[];}constContainer:React.FC=()=>{const[processings,setProcessings]=useState<ITaxonomyTerms[]>([]);const[productStatuses,setProductStatuses]=useState<ITaxonomyTerms[]>([]);const[filter,setFilter]=useState<FilterType>({processings:[],productStatuses:[],});useEffect(()=>{Client.taxonomy('processings').toPromise().then((response)=>{setProcessings(response.data.taxonomy.terms);});},[]);useEffect(()=>{Client.taxonomy('product_status').toPromise().then((response)=>{setProductStatuses(response.data.taxonomy.terms);});},[]);constmatches=(coffee:Coffee):boolean=>matchesTaxonomy(coffee,filter.processings,'processings')&&matchesTaxonomy(coffee,filter.productStatuses,'productStatuses');// To see how matchesTaxonomy can work see src/Utilities/CheckboxFilterconsttoggleFilter=(filterName:string,filterValue:string):void=>{setFilter((filter)=>({ ...filter,[filterName]:filter[filterName].includes(filterValue) ?filter[filterName].filter((x:string)=>x!==filterValue) :[...filter[filterName],filterValue],}));};.return(<div> ...<CheckboxFilter...onChange:(event)=>toggleFilter('processings',event.target.id),/> ...<ItemListingitems={items[language].filter((item:ItemDTO)=>matches(coffee))}/>... </div>);}
In Kontent.ai each language is identified by codename, in case of this project, it isen-US
andes-ES
.
Not every text of the application must be stored in Kontent.ai. Some strings, such as button texts, navigation texts, and so on, can be stored directly in the application. For those textsReact-intl is used. For every language, there is a JSON file insrc/Localization
folder.
React-intl
can not parse nested JSON objects and therefore the format of files iskey:value
. To load all files fromsrc/Localization
folder there is asrc/utilities/LocalizationLoader.ts
script.
// en-US.json{"LatestArticles.title":"Latest articles","LatestArticles.noTitleValue":"(Article has no title)","LatestArticles.noTeaserValue":"(Article has no teaser image)","LatestArticles.noSummaryValue":"No summary filled"// ...}
The language prefix is obtained from the URL in theLocalizedApp.tsx
and then it is propagated via IntlProvider to the whole application. Content language is then adjusted by modifyingClient
withlanguageParameter()
method to obtain items in a specific language. By default it useslanguage fallbacks set up in the project.
constComponent:React.FC=()=>{const{locale:language}=useIntl();useEffect(()=>{constquery=Client.items<ItemDTO>().type(projectModel.contentTypes.itemDTO.codename);if(language){query.languageParameter(language);} ...
You might want to request items based on the URL slugs. For more information check outKontent.ai/learn tutorial. An example in this application for this is provided insrc/Pages/About.tsx
page.
The showcase is not ideal, because it is using a combination of the language prefixes and localizable routes. You should try to stick with one of the approaches. Because it is hard to define the behavior (priority) for language setting clashes like `//articles/.
To deal with content that is not available in current language, this project uses method called language fallbacks. It will fetch the content in the language which set as fallback language in the Kontent.ai project and redirect the website to the URL with prefix of the given language. However, it is possible to disable language fallbacks by adding a filter ofsystem.language
to your query. For more information about getting localized content check thislink.
varquery=Client.items<AboutUs>().type(contentTypes.about_us.codename);if(this.language){query.languageParameter(this.language).equalsFilter('system.language','es-ES');}
For the not found resources, prefixed 404 pages are used for both languages. As the content on one page should be in one language, this approach might help you to optimize SEO. If language is not set in the URL the application uses the last used language, which is set in cookies.
You can use eg.surge to deploy your app live. Check out the step-by-step guide on ourblog.
We would like to express our thanks to the following people who contributed and made the project possible:
Would you like to become a hero too? Pick anissue and send us a pull request!
About
Sample React SPA utilizing the Kontent.ai Delivery API to fetch content.