In the tutorial, we will build REST API with Strapi, post our invoice items from our Next.js app to the backend, and then give users the option to print the Invoice and save it to their device. We will also work with Tailwind CSS to style our application, so it looks elegant.
Let take a look at a demo of what we are going to be building throughout this article:
This tutorial is beginner-friendly, but to follow along, you will need to have a basic knowledge of the following:
This section will focus on scaffolding our Strapi project, creating our invoices collections, and then making them accessible to our front-end application.
Creating a Strapi Project To scaffold a Strapi project, run either of the following commands in your terminal.
yarn create strapi-app invoice-generator-api --quickstart
# OR
npx create-strapi-app invoice-generator-api --quickstart
When this is done, cd
into your newly created Strapi project and run yarn develop
or npm run develop
to start the development server of our Strapi project.
Creating Invoice Collection
Next, we will create a new Collection Type that will store the data for each invoice item sent from our Next.js app.
Let's create a Collection Type called Invoice
with the necessary fields. To do this, navigate to Content-Types Builder, http://localhost:1337/admin/plugins/content-type-builder, on the admin dashboard and click on the Create new collection type
button and fill invoice
as the display name.
Click on the "Add another field" button, add a field with the named sender
, and choose an Email
type. This will receive the sender of the invoice email. Add another field name of billTo
and select a type of Text
.
Next, add an Email
type with the name shipTo
, dueDate with a type of Date
, note
with a type of Text
, invoiceItemDetails
with a type of JSON
, and lastly total
with. type of Number
Next, add an Email
type with the name shipTo
, dueDate with a type of Date
, note
with a type of Text
, invoiceItemDetails
with a type of JSON
, and lastly, total
with type of Number
.
When you are done setting up the fields in your collections, you should end up with this:
Setting up Roles and Permissions
Next, we need to set up our roles and permission to have access to our data from our Next.js App. To do this, navigate to Setting
→ Users & Permissions Plugin
→ Public
and then tick on the select all checkbox under the Permissions
section and click on the Save
button at the right top corner:
We have successfully created our API with Strapi. Let's move over to the frontend of our app and build the interface and frontend functionality with Next.js(https://strapi.io/integrations/nextjs-cms. To bootstrap a Next.js app, run either of the following commands:
npx create-next-app invoice-generator
# or
yarn create next-app invoice-generator
We will be using Tailwind CSS to build out our app's interface and install it in our Next.js app. Run the following command at the root of your newly created Next.js app on your terminal to install Tailwind CSS:
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
After that, run the following command to create the necessary config files for tailwind:
npx tailwindcss init -p
Next, add the following import
statement at the top of your pages/_app.js
file.
1 import 'tailwindcss/tailwind.css'
Building the invoice interface
Now that we have the interface of our app with Next.js and style it with Tailwind CSS. This is the part of the interface we are going to be building first:
Add the following line of code to your index.js
:
1 <form className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
2 <div className="mb-4">
3 <label
4 className="block text-gray-700 text-sm font-bold mb-2"
5 htmlFor="sender"
6 >
7 Your email address
8 </label>
9 <input
10 className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
11 id="sender"
12 name="sender"
13 type="email"
14 required
15 placeholder="Who is this invoice from? (required)"
16 // onChange={handleInputChange}
17 />
18 <label
19 className="block text-gray-700 text-sm font-bold my-3"
20 htmlFor="billTo"
21 >
22 Bill To
23 </label>
24 <textarea
25 className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
26 id="billTo"
27 name="billTo"
28 type="email"
29 required
30 placeholder="Who is this invoice to? (required)"
31 // onChange={handleInputChange}
32 />
33 </div>
34 <div className="mb-6">
35 <label
36 className="block text-gray-700 text-sm font-bold mb-2"
37 htmlFor="shipTo"
38 >
39 Ship To
40 </label>
41 <input
42 className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
43 id="shipTo"
44 name="shipTo"
45 type="email"
46 required
47 placeholder="Client's email"
48 // onChange={handleInputChange}
49 />
50 </div>
51 </form>
Notice how the *onChange*
event handler is commented out on the code above. This is because we've not implemented the handler yet. We will do that later.
Next, let's build this row of our Invoice where users can add multiple invoice items, the quantity, and price as well and remove unwanted invoice items:
Add the following lines of code inside of the form we created above:
1 {invoiceFields.map((invoiceField, i) => (
2 <div
3 className="flex justify-center items-center"
4 key={`${invoiceField}~${i}`}
5 >
6 <label
7 className="block text-gray-700 text-sm font-bold mb-2 w-full mr-5"
8 htmlFor={`${invoiceField.itemDescription}~${i}`}
9 >
10 Invoice Item
11 <input
12 className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
13 id={`${invoiceField.itemDescription}~${i}`}
14 name="itemDescription"
15 type="text"
16 spellCheck="false"
17 // value={invoiceField.itemDescription}
18 // onChange={(event) => handleChange(i, event)}
19 />
20 </label>
21 <label
22 className="block text-gray-700 text-sm font-bold mb-2 w-full mr-5"
23 htmlFor={`${invoiceField.qty}~${i}`}
24 >
25 Quantity
26 <input
27 className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
28 id={`${invoiceField.qty}~${i}`}
29 name="qty"
30 type="number"
31 spellCheck="false"
32 // value={invoiceField.qty}
33 // onChange={(event) => handleChange(i, event)}
34 />
35 </label>
36 <label
37 className="block text-gray-700 text-sm font-bold mb-2 w-full mr-5"
38 htmlFor={`${invoiceField.price}~${i}`}
39 >
40 Unit Price
41 <input
42 className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
43 id={`${invoiceField.price}~${i}`}
44 name="price"
45 type="tel"
46 spellCheck="false"
47 // value={invoiceField.price}
48 // onChange={(event) => handleChange(i, event)}
49 />
50 </label>
51 <button
52 className="bg-red-500 hover:bg-red-700 h-8 px-5 py-3 flex items-center justify-center text-white font-bold rounded focus:outline-none focus:shadow-outline"
53 type="button"
54 // onClick={() => handleRemoveInvoice(i)}
55 >
56 Remove
57 </button>
58 </div>
59 ))}
60 <button
61 className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
62 type="button"
63 // onClick={addInvoiceItem}
64 >
65 Add Item
66 </button>
Notice we have some lines of code commented out in our form up there. This is what we will use to get the values from our input field. We will also create these event handlers later in this section.
Next, let's create the state in our app where the invoice items we've created from our form will come from. Don't forget to import useState
from react
:
1 const [invoiceFields, setInvoiceFields] = useState([
2 {
3 itemDescription: '',
4 qty: '',
5 price: '',
6 },
7 ]);
Let's move on to creating the last part of our invoice user interface:
Add the following lines of code to get the interface above. We will implement the feature to get the data from input field and manage state as well as sending it to the API we created later.
1 <div className="my-6 flex flex-col">
2 <label
3 htmlFor="note"
4 className="block text-gray-700 text-sm font-bold mb-2 w-full"
5 >
6 Invoice Notes
7 </label>
8 <textarea
9 id="note"
10 name="note"
11 // onChange={handleInputChange}
12 className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
13 />
14 </div>
15 <div className="mb-6 flex justify-between font-bold text-xl">
16 <p>Total:</p>
17 {/* <p>{total}</p> */}
18 </div>
19 <div className="flex items-center justify-between">
20 <button
21 className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
22 type="button"
23 // onClick={handleSendInvoice}
24 >
25 Send Invoice
26 </button>
27 <button
28 className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
29 type="button"
30 // onClick={handlePrintInvoice}
31 >
32 Download Invoice
33 </button>
34 </div>
Get values from our invoice form fields
This section will get the values from our React form using the useReducer and useState hooks. Let’s create a reducer function and then dispatch the function to get the values from our input fields:
1 // export default function Home() {
2 const initialState = {
3 sender: '',
4 billTo: '',
5 shipTo: '',
6 dueDate: '',
7 note: '',
8 };
9 function reducer(state = initialState, { field, value }) {
10 return { ...state, [field]: value };
11 }
12 const [formFields, dispatch] = useReducer(reducer, initialState);
Now that we've created our reducer function let's use the dispatch function returned to us by the useReducer
hook to get the value of our input fields. To do this, we will create a function and call the dispatch method there and add an onChange
event to our input field that will call our function:
1 // we will add this function to the onChange event in the input field in our invoice
2 const handleInputChange = (e) => {
3 dispatch({ field: e.target.name, value: e.target.value });
4 };
We already have the handleInputChange
function we just created attached to the form field in the invoice input field, so uncomment it out, and you should get access to the values of the input fields.
Let's create a separate event handler to get the value of the input fields of this dynamic section in our input field:
1 const handleChange = (index, event) => {
2 const values = [...invoiceFields];
3 if (event.target.name === 'itemDescription') {
4 values[index].itemDescription = event.target.value;
5 } else if (event.target.name === 'qty') {
6 values[index].qty = event.target.value;
7 } else if (event.target.name === 'price') {
8 values[index].price = event.target.value;
9 }
10 setInvoiceFields(values);
11 };
Above, we are checking for the name of the input field the user interacts with and then change the value of the input field to be in sync with what we have in our useState
:
1 const [invoiceFields, setInvoiceFields] = useState([
2 {
3 itemDescription: '',
4 qty: '',
5 price: '',
6 },
7 ]);
We are checking if the name
attribute of the input field is that of the qty
. For example, we want to set the index of that particular input field in our state to be the value of what the user enters.
Add invoice items
Let's add the functionality to add invoice items to our array of invoiceFields
in our useState
hook.
Here, we call the setInvoiceFields
function returned from the useState
hook and then used the spread operator to copy what we have in our state and then add the object to what we have already in our state.
1 const addInvoiceItem = () => {
2 setInvoiceFields([
3 ...invoiceFields,
4 {
5 itemDescription: '',
6 qty: '',
7 price: '',
8 },
9 ]);
10 }
Next, we have to call our function and make sure the total updates only when necessary. To do this, we will call the getTotal
function in the useEffect hook.
1 useEffect(() => {
2 getTotal();
3 }, [total]);
Remove invoice items
Let's add the functionality to remove invoice items from our array of invoiceFields
in our useState
hook.
To do this, we need to bass the index
of the invoice item clicked by the user to our click function as seen below:
1 <button className="bg-red-500 hover:bg-red-700 h-8 px-5 py-3 flex items-center justify-center text-white font-bold rounded focus:outline-none focus:shadow-outline"
2 type="button"
3 onClick={() => handleRemoveInvoice(i)}
4 >
5 Remove
6 </button>
Notice this line of code; if (values.length === 1) return false;
we don’t want to remove the invoice item if it’s the only item in our invoice. Then we want to use the splice array method to remove the item that the user clicks and update the state.
1 const handleRemoveInvoice = (index) => {
2 const values = [...invoiceFields];
3 if (values.length === 1) return false;
4 values.splice(index, 1);
5 setInvoiceFields(values);
6 };
Invoice Computation Item
Now let's compute the total price for the invoice item users will add. To achieve this, we will use the useState
hook.
1 const [total, setTotal] = useState(0);
Notice we are using the forEach
method iterate over each of the items in the invoiceFields
array and get the quantity and price multiply both numbers and call the setTotal
method and pass the computed values to it.
1 const getTotal = () => {
2 let computedTotal = 0;
3 invoiceFields.forEach((field) => {
4 const quantityNumber = parseFloat(field.qty);
5 const rateNumber = parseFloat(field.price);
6 const amount =
7 quantityNumber && rateNumber ? quantityNumber * rateNumber : 0;
8 computedTotal += amount;
9 });
10 return setTotal(computedTotal);
11 };
This section will send our data from our frontend to the backend we've set up earlier on. We will use Axios to make HTTP requests.
Let's go ahead and install Axios. Run the following command in the terminal to install the package:
npm install axios
# or
yarn add axios
Then we need to send the invoice items to our server. Notice the window.print()
method we are using. We use it to open the print dialog on our browser after we’ve sent the request to our API and gotten a response.
1 const handleSendInvoice = async () => {
2 try {
3 let { billTo, dueDate, note, sender, shipTo } = formFields;
4 const { data } = await axios.post('http://localhost:1337/invoices', {
5 billTo,
6 dueDate,
7 note,
8 sender,
9 shipTo,
10 invoiceItemDetails: invoiceFields,
11 total,
12 });
13 window.print();
14 } catch (error) {
15 console.error(error);
16 }
17 };
Let's create a handler where users can generate invoices without sending the request to the API. To do this, you'll have to fill in your invoice details and click on the "Download invoice" button. This button will trigger an onClick
event that calls the window.print()
method.
1 const handlePrintInvoice = () => {
2 window.print();
3 };
In this article, we've seen how powerful and very easy to use Strapi is. We've seen how to add various field types ranging from email, Date, Number, and more to our collection. Setting up a backend project is like a walk in the park, very simple and easy. By just creating our collections, Strapi will provide us with endpoints we need following best web practices.
We also built our frontend application with Next.js and styled our invoice app with Tailwind CSS.
You can find the complete code used in this tutorial for the frontend app, and the backend code is available on GitHub. You can also find me on Twitter, LinkedIn, and GitHub.
By building and deploying your own invoice generator app, you've used Next.js, Strapi, and Tailwind CSS to create a functional and attractive solution. Understanding the benefits of headless CMS and the many reasons to use Strapi can help you further enhance your applications. Strapi offers plans to suit your business needs. Our headless CMS solutions provide performance and flexibility with enterprise options.
Feel free to drop a comment to let me know what you thought of this article.
I love to call myself a JavaScript Developer with industry experience in building scalable and performant applications that run on the web and your smartphone with cutting-edge technology. I author meaningful technical content, regularly.