This article will show you how to build a Temperature Converter with Next.js and Tailwind CSS as frontend and Strapi headless CMS as backend. You can find a link to the finished frontend code, as well as the finished backend
Before starting this tutorial, you need to have
Next.js is an awesome React framework for building highly dynamic applications. It comes with pre-rendering, automatic code-splitting amongst many other great features out of the box.
Tailwind is a utility-first CSS framework for rapidly building custom user interfaces. By using Tailwind, we can write our css directly in our HTML classes. This leads to a faster development time.
Strapi is a Node.js open-source headless CMS that allows us to develop APIs and manage content easily without the hassle of building out a project from scratch.
We can easily build out APIs faster and consume the contents via APIs using any REST API client or GraphQL.
To setup a new Strapi Project is quite straightforward and simple as running these few commands:
npx create-strapi-app temperature-converter --quickstart
Change temperature-converter
to the preferred name of your project
Nb: During the setup, we would not be using any Strapi template
This will install and create a Strapi application and set up the project locally.
After installation, the browser would open a page on localhost:1337 which would prompt to set up first admin account to proceed with Strapi.
Next, we will create a new collection type that will store the details of each temperature converter. In this article, we will create a collection type called ‘temperature’ that has these fields: from, to, multiplier, offset, offset_add
Clicking “Continue” would bring up another screen to select the fields for this collection. Choose the “Text” field from the list and provide from
as its name.
Click “Advanced settings” and check the “Required field” box to ensure this field is required when creating a new temperature converter.
We click on the Add another field to add the remaining fields. Below is a table showing the properties for each field in this collection:
Field Name | Field Type | Required |
---|---|---|
from | short text | true |
to | short text | true |
multiplier | number(decimal) | true |
offset | number(float) | true |
offset_add | number(decimal) | true |
We would now need to seed our collection to have the predefined parameters we need in our formula.
To add data to the collection, we select the Temperature Collection on the left sidebar, click “Add New Temperature” and fill in the details.
After Seeding we would have the collection populated as such:
By default, whenever you create an API, Strapi creates six endpoints from the name given to the API. The endpoints generated for temperature should look like this:
By default, they’re all going to be restricted from public access. We need to tell Strapi that you’re okay with exposing these checked endpoints to the public. Go to Settings > Users & Permissions Plugin> Roles and click to edit the Public Role. Next, scroll down to permissions and check find
for Temperature.
This endpoint: http://localhost:1337/temperatures should now be available
Create a Next.js app
To create a Next.js app, open your terminal, cd
into the directory you’d like to create the app in, and run the following command:
npx create-next-app -e with-tailwindcss nextjs-temperature
This would also configure Tailwind CSS with the project.
Run the Next.js development server
Next we cd
into the newly created directory, in our case that would be nextjs-temperature
1 cd nextjs-temperature
After which we start up the development server, by running this command:
1 npm run dev
If everything was set up fine, the next.js server should now be running on http://localhost:3000 we should get this shown on our browser:
After setup we should have a folder structure such as this:
Next, we create the temperature converter page. We open the index.js
file in our favourite text editor, we delete its contents and replace them with the file content below:
1 import Head from 'next/head'
2 import { useState, useEffect } from 'react'
3 import { converter, fetchQuery, getUniqueTemp } from '../utils/helper'
4 export default function Home({ temperatures }) {
5 const [answer, setAnswer] = useState('')
6 const [from, setFrom] = useState('C')
7 const [to, setTo] = useState('F')
8 const [temperature, setTemperature] = useState(1)
9 const [options, setOptions] = useState([])
10 useEffect(() => {
11 setOptions(getUniqueTemp(temperatures, 'from'))
12 }, [temperatures])
13
14 const handleSubmit = (e) => {
15 e.preventDefault()
16 setAnswer(`${converter(temperatures, from, to, Number(temperature))} ${to}`)
17 }
18
19 return (
20 <div className="flex flex-col items-center justify-center min-h-screen py-2">
21 <Head>
22 <title>Temperature Converter</title>
23 <link rel="icon" href="/favicon.ico" />
24 </Head>
25 <main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
26 <h1 className="text-6xl font-bold">
27 Temperature {' '}
28 <a className="text-blue-600" href="https://nextjs.org">
29 Converter
30 </a>
31 </h1>
32 <form className="space-y-4 text-gray-700" onSubmit={handleSubmit}>
33 <div className="flex flex-wrap">
34
35 </div>
36 <div className="flex flex-wrap -mx-2 space-y-4 md:space-y-0">
37 <div className="w-full px-2 md:w-1/2">
38 <label className="block mb-1">From</label>
39 <select className="w-full h-10 pl-3 pr-6 text-base placeholder-gray-600 border rounded-lg appearance-none focus:shadow-outline" placeholder="Select From" value={from} onChange={ (e) => { setFrom(e.target.value)}}>
40 {options.map(e => (
41 <option value={e} key={e}>{e}</option>
42 ))}
43 </select>
44 </div>
45 <div className="w-full px-2 md:w-1/2">
46 <label className="block mb-1" >To</label>
47 <select className="w-full h-10 pl-3 pr-6 text-base placeholder-gray-600 border rounded-lg appearance-none focus:shadow-outline" placeholder="Select To" value={to} onChange={ (e) => { setTo(e.target.value)}}>
48 {options.map(e => (
49 <option value={e} key={e}>{e}</option>
50 ))}
51 </select>
52 </div>
53 </div>
54 <div className="flex flex-wrap -mx-2 space-y-4 md:space-y-0">
55 <div className="w-full px-2 md:w-1/2">
56 <label className="block mb-1">Value</label>
57 <input className="w-full h-10 px-3 text-base placeholder-gray-600 border rounded-lg focus:shadow-outline" type="number" value={temperature} onChange={ (e) => { setTemperature(e.target.value)}}/>
58 </div>
59 <div className="w-full px-2 md:w-1/2">
60 <input className="w-full h-10 px-3 my-7 cursor-pointer text-base placeholder-gray-600 border rounded-lg focus:shadow-outline hover:bg-blue-600 hover:text-white" type="submit" value="Convert"/>
61 </div>
62 </div>
63 </form>
64 <div>
65 Result is : {answer}
66 </div>
67 </main>
68 </div>
69 )
70 }
71 export async function getStaticProps() {
72 const temperatures = await fetchQuery('temperatures')
73 return {
74 props: {
75 temperatures
76 }
77 }
78 }
This file is the entry point to our app. We use it to create out a design for the app, and also set up our functionalities to handle the conversion process. We proceed to create a utils folder at the root of our project and create a file called helper.js
in it, this file would be where we place all helper functions.
This helper.js
file would contain basic helper functions that would help us convert the temperature as well as get data from the Strapi backend server.
1 const baseUrl = process.env.BASE_URL || 'localhost:1337'
2 export const converter = (temperatures, from, to, val) => {
3 let temperature = {}
4 let answer = 0
5 switch(`${from}-${to}`){
6 case 'F-C':
7 temperature = getFields(temperatures, from, to)
8 answer = (((val + temperature.offset) * temperature.multiplier ) + temperature.offset_add)
9 break;
10 case 'C-F':
11 temperature = getFields(temperatures, from, to)
12 answer = (((val + temperature.offset) * temperature.multiplier ) + temperature.offset_add)
13 break;
14 case 'C-K':
15 temperature = getFields(temperatures, from, to)
16 answer = (((val + temperature.offset) * temperature.multiplier ) + temperature.offset_add)
17 break;
18 case 'K-C':
19 temperature = getFields(temperatures, from, to)
20 answer = (((val + temperature.offset) * temperature.multiplier ) + temperature.offset_add)
21 break;
22 case 'F-K':
23 temperature = getFields(temperatures, from, to)
24 answer = (((val + temperature.offset) * temperature.multiplier ) + temperature.offset_add)
25 break;
26 case 'K-F':
27 temperature = getFields(temperatures, from, to)
28 answer = (((val + temperature.offset) * temperature.multiplier ) + temperature.offset_add)
29 break;
30 default:
31 answer = val
32 break;
33 }
34 return answer
35 }
36 export const getFields = (array, from, to) => {
37 return array.find(x => x.from === from && x.to === to)
38 }
39 export const fetchQuery = async (path, params = null) => {
40 let url
41 if (params !== null) {
42 url = `${baseUrl}/${path}/${params}`
43 } else {
44 url = `${baseUrl}/${path}`
45 }
46 const response = await fetch(`http://${url}`)
47 const data = await response.json()
48 return data
49 }
50 export const getUniqueTemp = (arr, key) => {
51 let keys = arr.map(function(item) { return item[key]; })
52 return [...new Set(keys)]
53 }
The finished app looks like this:
And that's it, we saw how to set up a temperature converter using Strapi, Next.js, and Tailwind CSS. This article can be taken further to be used as a base for other kinds of conversions. This goes to show what we can achieve using this setup and the possibilities therein.
A full-stack developer, technical writer, and lover of Jamstack, passionate about lifelong learning, open and inclusive communities, and a big advocate of open source.