Category Archives: TailwindCSS

Responsive Mobile Navigation With NextJS and TailwindCSS

Responsive Mobile Navigation With NextJS and TailwindCSS

In this tutorial, we’ll be using Next.js and TailwindCSS to build a responsive global navigation bar for your next project. This tutorial will walk you through the steps to set up your project, create components and add a global navbar in Next.js project using TailwindCSS!

The goal of having a mobile navigation is to make sure that content is always at users’ fingertips as they browse your application regardless of the devices.

Next.js

Next.js is a framework that makes the creation of React apps extremely easy and efficient.

Next.js is an open-source development framework built on top of React.js. It is React based framework which have various functionalities to power up both server-side rendering and generating client side static websites.

Next.js gives you the best developer experience with all the features it present for any production ready apps. Features such as hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching give developers a seamless development experience.

You can learn more about Nextjs and its newest features here.

TailwindCSS

TailwindCSS is a utility-first CSS framework that helps you create responsive layouts and design systems with ease. TailwindCSS is utility-based low level CSS framework intended to ease building web applications much faster and more efficiently. TailwindCSS is so popular nowadays, because it helps build websites without ever leaving your HTML files.

The purpose of this post is to show how easy and intuitive it can be to make a responsive navbar in NextJS with the help of TailwindCSS. So let’s begin. Before we start writing some code, we need to do some initial configuration for tailwind and Nextjs.

Setup and Configuration

To start with, we need to install NextJS with NextCli, using npm or yarn. In our case we prefer to use npm. Start by creating a new Next.js project if you don’t have one set up already. Follow this tutorial for complete installation guide of Nextjs and TailwindCSS project.

Creating Pages

Next, create few pages for the application. We are having home, about, projects and contact page. In the pages folder we are going to create all the pages so we can call them inside the navebar. In addition, create a component called MenuItems.js. Using props we will pass showMenu function and active status.

const MenuItems = ({ showMenu, active }) => {
  return (
    <ul
      className={
        active
          ? "flex-col flex items-center fixed inset-0 left-1/4 uppercase bg-black/40 backdrop-blur-lg gap-8 justify-center p-8 md:hidden"
          : "hidden"
      }
    >
      <Close onClick={showMenu} className="cursor-pointer" />
      <li>
        <Link href="/">
          <a>Home</a>
        </Link>
      </li>
      <li>
        <Link href="/projects">
          <a>Projects</a>
        </Link>
      </li>

      <li>
        <Link href="/about">
          <a>About</a>
        </Link>
      </li>
      <li>
        <Link href="/contact">
          <a>Contact</a>
        </Link>
      </li>
    </ul>
  );
};

Building Our Navbar

Now create a components folder in your root directory, then create all the components in that folder. Create Header.js file inside this folder.

React useState hooks is used identify the current state of the menu bar. By default we let the menu bar for mobile hidden using active state false. We use a function named showMenu to hide and show the menu for respective devices.

function Header() {
  const [active, setActive] = useState(false);

  const showMenu = () => {
    setActive(!active);
  };

Now it is time to install Material-ui icons using npm. To display the menu we are using a clickable button named MenuOutlined icon from material-ui icons. We use onClick property and then call showMenu function inside the MenuOutlined.

<nav>
    <div className="absolute right-6 md:hidden top-6 scale-150">
      <MenuOutlined
        onClick={showMenu}
        className="scale-150 cursor-pointer"
      />
    </div>

    <ul className="hidden md:flex gap-8 p-6 uppercase bg-white/10">
      <li>
        <Link href="/">
          <a>Home</a>
        </Link>
      </li>
      <li>
        <Link href="/">
          <a>Testimonials</a>
        </Link>
      </li>
      <li>
        <Link href="/">
          <a>Information</a>
        </Link>
      </li>

      <li>
        <Link href="/about">
          <a>About</a>
        </Link>
      </li>
      <li>
        <Link href="/contact">
          <a>Contact</a>
        </Link>
      </li>
    </ul>

    <MenuItems showMenu={showMenu} active={active} />
</nav>

Making Navbar Appear on All Pages

Now we have done our navbar. But it is important to use a common navbar in every page of our application. To make it simple we can import navbar in the root level file _app.js.

import "../styles/globals.css";
import Head from "next/head";

import Header from "../components/Header";

function MyApp({ Component, pageProps }) {
  return (
    <>
      <Head>
        <title>Navbar Example</title>
      </Head>
      <Header />
      <Component {...pageProps} />
    </>
  );
}

export default MyApp;

Now you have a working responsive navbar.

You can have full code here. Thanks for reading!

Install Tailwind CSS with Next.js

Install Tailwind CSS with Next.js

Setting up Tailwind CSS in a Next.js v10+ project.

This tutorial will walk you through the steps by steps to install and configure a Next.js project with TailwindCSS.

TailwindCSS

Tailwind is a utility-first CSS framework that provides a set of ready-to-use mixins, so it doesn’t require any of the usual CSS configuration. TailwindCSS is used for frontend styling, as it helps build websites without ever leaving your HTML files.

NextJS

Next.js is a minimalistic open-source framework for server-rendered React applications, built on top of ReactJs, allowing developers to create JavaScript applications that work both in the browser and in Node environments (e.g., server rendering).

Create your project

Create a new Next.js project using command line tool. You can use NextJs official documentation to create brand new Nextjs app.

npx create-next-app my-project
cd my-project

Install Tailwind CSS

Install TailwindCSS and its peer dependencies via npm. You can also use yarn instead of npm. Now run the init command as shown below to generate tailwind.config.js and postcss.config.js. These files are helpful when you want to configure more things regarding TailwindCSS for your application.

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Configure your template paths

Add the paths to all of your template files in your tailwind.config.js file. You can use your own CSS, external packages and plugins in your project using tailwind.config.js.

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

Add the Tailwind directives to your CSS

Add the @tailwind directives for each of Tailwind’s layers to your ./styles/globals.css file. Now basic setup is completed.

@tailwind base;
@tailwind components;
@tailwind utilities;

It is time to run your build process with npm run dev.

npm run dev

Start using Tailwind in your project

Start using Tailwind’s utility classes to style your content.

export default function Home() {
  return (
    <h1 className="text-3xl font-bold underline">
      Hello world!
    </h1>
  )
}

How to Add Custom Fonts to NextJS and Tailwind CSS Application

Add Custom Fonts to NextJS and Tailwind CSS Application

Tailwind CSS offers powerful capabilities to build visually appealing websites in a short time frame. To give your website a unique look and feel, you can choose to add custom fonts to NextJS project using Tailwind configuration.

Setting up a custom font in Next.js using Tailwind CSS is fairly easy. It needs 3 easy steps.

  • Installation and setting up _document.js
  • Declaring custom font family in tailwind.config.js
  • Using it in your components and pages.

For this tutorial, we will use Montserrat, a free Google Font. So let us begin installation process.

Create Your NextJs Project

The quickest way to start using Tailwind CSS in your Next.js project is to use the Next.js + Tailwind CSS Example. This will automatically configure your Tailwind setup based on the official Next.js example. If you’d like to configure Tailwind manually, continue with the rest of this guide.

Create your project

Start by creating a new Next.js project if you don’t have one set up already. The most common approach is to use Create Next App.

npx create-next-app nextjs-tailwind-tips
cd nextjs-tailwind-tips

If everything has goes well, you will see something like this on your terminal.

Install Tailwind CSS

Install tailwindcss and its peer dependencies via npm, and then run the init command to generate both tailwind.config.js and postcss.config.js.

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Configure your template paths

Add the paths to all of your template files in your tailwind.config.js file.

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

Add the Tailwind directives to your CSS

Add the @tailwind directives for each of Tailwind’s layers to your ./styles/globals.css file.

@tailwind base;
@tailwind components;
@tailwind utilities;

Add Google Font to _document.js File

A custom Document can update the <html> and <body> tags used to render a Page. This file is only rendered on the server, so event handlers like onClick cannot be used in _document.

To override the default Document create a new custom document file _document.js in your pages folder next-project/pages/ and set it up with the following code:

Go to Google Fonts and search for the specific font you like. For this tutorial, we will use Montserrat, a free Google Font. Select the style variants from thin (100) to bold (900). Copy the link provided by Google and past in between the Head tags.

import Document, { Html, Head, Main, NextScript } from "next/document";

function MyDocument() {
  return (
    <Html>
      <Head>
        <link
          href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;200&display=swap"
          rel="stylesheet"
        />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

export default MyDocument;

Now, it’s time to configure the tailwind.config.js file. Go to Add tailwind.config.js and add Montserrat as the font family for your app. Also remember to add defaulTheme for the app as shown below.

/** @type {import('tailwindcss').Config} */
const defaultTheme = require("tailwindcss/defaultTheme");

module.exports = {
  mode: "jit",
  purge: ["./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {
      fontFamily: {
        Montserrat: ["Montserrat", ...defaultTheme.fontFamily.sans],
      },
    },
  },
  variants: {
    extend: {},
  },
  plugins: [],
};

Start Using Custom Font

Go to your Components or Pages, in this case for simplicity we are using _app.js file to custom font. Add className=”font-fontname” to the element. The fontName here refers to the name we gave to the font family in the previous step in this case Montserrat.

import Head from "next/head";
import Image from "next/image";

export default function Home() {
  return (
    <div>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main>
        <h1 className="w-full text-center py-12 font-Montserrat text-3xl font-bold">
          Hello world! Im Montserrat Font
        </h1>
      </main>
    </div>
  );
}

Now you will be able to see the custom font you just added to your app.

Code is available on GitHub repo.

How to Build a Multiselect Dropdown Component Using React-select

React select dropdown tutorial using react-select. (1)

In this tutorial, you will learn how to use react-select library to create a dropdown selection in your React app. Before that, let’s first understand what React-select is and why should you use this library in your React.js project.

React-select

React-select is an easy to use dropdown library create by Jed Watson and few other awesome contributors. It is a powerful library, offers various features such as multi-select, autocomplete and many more. This is a perfect choice for your next Reactjs project, providing numerous dynamic functionalities to the dropdown components including search and filter functionality, animation, easy accessibility and faster loading time.

Features provided by React-select package include:

  • Flexible approach to data with customizable functions.
  • It handle large number of dataset.
  • Simple customization with API support.
  • Controllable state props and modular architecture.
  • Manage component state easily.
  • CSS styling with emotion support. Provide CSS animation support for components.
  • Long-requested features like option groups, portal support, animation, and more

Step 1: Install React and other libraries

Dependencies used for this project.

  • React-Select Library
  • TailwindCSS for CSS and styling (optional- you can use any styling library)

Run the following command to install a brand new React project. You can either use yarn or npm, but for this tutorial, npx is used. This will create a React app for us.

npx create-react-app react-select

Change the directory and get inside to the project folder. You can always clean the project just a little bit. Remove the files you do not required for this project.

cd react-select

Install Tailwind CSS

Install TailwindCSS and its peer dependencies via npm, and then run the init command to generate both tailwind.config.jsand postcss.config.js.

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Configure your template paths

Add the paths to all of your template files in your tailwind.config.jsfile.

module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

Add the Tailwind directives to your CSS

Add the @tailwinddirectives for each of Tailwind’s layers to your ./src/index.cssfile.

@tailwind base;
@tailwind components;
@tailwind utilities;

Start using Tailwind in your project

Start using Tailwind’s utility classes to style your content and it will reflects the changes you make to the app.

Install React-Select Library

Now, this is important step. We need to install React-select package. For that simply run the following command.

npm i react-select

Once it is installed, you can now import the react-select module any where in our project. For simplicity it is imported in src/App.js file.

Now create a function that will handle our selected value. Name it setHandle and call it on the component. It will change the current value once user click to the dropdown.

import "./App.css";
import React, { useState, Component } from "react";
import Select from "react-select";

const Hotels = [
  { value: 1, label: "Coral Beach Maldives" },
  { value: 2, label: "Ilaa Beach Maldives" },
  { value: 3, label: "Finolhu" },
  { value: 4, label: "Arena" },
  { value: 5, label: "Kaani Beach Hotel" },
];

function App() {
  const [selectedOptions, setSelectedOptions] = useState(null);

  const setHandle = (e) => {
    setSelectedOptions(Array.isArray(e) ? e.map((hotel) => hotel.label) : []);
  };

  return (
    <div className="mx-auto container py-8">
      <h1 className="text-sm">Select Hotels</h1>
      <div className="flex flex-wrap items-center lg:justify-between justify-center">
        <div className=" px-2	">
          <Select options={Hotels} onChange={setHandle} isMulti />
        </div>
        <div>{selectedOptions}</div>
      </div>
    </div>
  );
}

export default App;

An array named Hotels is created, it then pass the hotel list to the dropdown. Hotel names is displayed when a user clicks on the dropdown and select element with the help of the react-select library.

There are many other properties available and common props you may want to specify include:

  • autoFocus – focus the control when it mounts
  • isDisabled – disable the control
  • isMulti – allow the user to select multiple values
  • isSearchable – allow the user to search for matching options
  • name – generate an HTML input with this name, containing the current value
  • onChange – subscribe to change events
  • options – specify the options the user can select from
  • placeholder – change the text displayed when no option is selected

React Multi Select Dropdown

Multi select option is one of the popular properties provided by this library. let us understand how this is used in a React project. It is actually very easy, simply you need to add isMulti prop to select various value in a select dropdown.

<Select options={Hotels} onChange={selHandle} isMulti />

Thats all for now! You can find code for this tutorial in this GitHub repo

How to Add Tailwind CSS to Your Reactjs Project

Tailwind CSS to ReactJS project

Tailwind CSS is a utility-first CSS framework which is used to make your website more responsive and beautiful. It is well known modern CSS frameworks which helps to speed up the development and styling process significantly. If you’re new to Tailwind CSS please follow the official documentation of Tailwind CSS and find a good starting point at the project’s homepage at TailwindCSS.

Setting up your React project with Tailwind CSS is so simple and comprises only very few steps. In this tutorial you will learn step-by-step approach of installing Tailwind CSS into your React project and get started using Tailwind’s CSS classes for styling.

Step 1: Creating Your React Project

Creating your new React.js project is the very first step. The easiest way to create a new project is to use the create-react-app script on the command line.

npx create-react-app react-app-with-tailwind

Now, cd into the working directory.

cd react-app-with-tailwind

If everything goes well, you should be able to see your react project on the web browser when you run the following command.  

npm run start

Step 2: Install Tailwind CSS

Now install tailwindcss and its peer dependencies via npm, and then run the init command to generate both tailwind.config.js and postcss.config.js.

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Tailwind will create two files. You need to make small changes so it will works well for our Reactjs project.

  • tailwind.config.js
  • postcss.config.js

Step 4: Configuring Template Files

You need to specify the path to our Reactjs project files by adding the following configuration setting inside tailwind.config.js. Make sure to add the paths to all of your template files in your tailwind.config.js file.

module.exports = {
   content: [
     "./src/**/*.{js,jsx,ts,tsx}",
   ],
   theme: {
     extend: {},
   },
   plugins: [],
 }

Step 5: Add the Tailwind directives to your CSS

Now add the @tailwinddirectives for each of Tailwind’s layers to your ./src/index.css file.

@tailwind base;
@tailwind components;
@tailwind utilities;

That’s all. You’re good to go! Let’s make use of Tailwind’s CSS classes within our main React component in App.js.

Step 6: Use Tailwind CSS In Your React App

Add the following code to App.js. Start the development web server by using the following command. Now you should be able to see the following result in the browser.

<div className="container mx-auto bg-gray-200 rounded-xl shadow border p-8 m-10">
      <p className="text-3xl text-gray-700 font-bold mb-5">
        Welcome!
      </p>
      <p className="text-gray-500 text-lg">
        React and Tailwind CSS in action
      </p>
    </div>
npm run start

You can find code for this tutorial in this GitHub repo

Implement Load More Pagination in React

Implement Load More Pagination in React

Introduction

After Covid-19, Pandemic and now Russia-Ukraine War, so many things happening unexpectedly😔  but thats another story lets focus on our topic for today.

In this article, we will go through how to implement Load more functionality for your next React.js project.

Demo of what we are working on today…👇


Why we need Load more functionality?


For example, you have an e-commerce app and you may need to load products from Rest API or from any other backend database. If we only have 10 or 20 products, it will be easy to fetch them all in just one request. However, if you have hundred and thousands of products sometime even millions, you have to implement pagination to reduce the request hitting on the server. It is important to reduce latency and server load so that the app significantly improves the performance.

So if you want display so many data such as products list, items or blog posts on your web page then you need to implement pagination. For this reason we are learning how to implement basic Load more functionality for in this article. Keep in mind in this example, we will not use any server side rending rather fetch products locally for simplicity.


Steps to implement load more pagination in React

  1. Create a Next.js app
  2. Install TailwindCSS and Configuration
  3. Design the app
  4. Implement load more button functionality
  5. Output

1. Create a Next.js app

Start by creating new Next.js project with TailwindCSS. The quickest way to start using Tailwind CSS in your Next.js project is to use the Next.js + Tailwind CSS Example.


npx create-next-app load-more
cd load-more

2. Install TailwindCSS and Configuration

Install tailwindcssand its peer dependencies via npm, and then run the init command to generate both tailwind.config.js and postcss.config.js.


npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Configure your template paths


module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

Add the Tailwind directives to your CSS

Add the @tailwinddirectives for each of Tailwind’s layers to your ./styles/globals.css file.


@tailwind base;
@tailwind components;
@tailwind utilities;

3. Design the app

Now let’s design the app. We will display list of groceries on the home page. Each product consists of item name, category and image. We will create few components and pages. We start with index.js page. This is main file for our app because it consists of <FreshProd /> component which is responsible to display all the products.


import Head from "next/head";
import Image from "next/image";
import Link from "next/link";
import FreshProd from "../components/FreshProd";

export default function Home() {
  return (
    <main className="container mx-auto px-8 sm:px-12">
      <section className="py-4">
        <div className="flex  items-center justify-between">
          <h2 className="text-md sm:text-2xl font-extrabold py-8">
            Stock Up on Fresh Favorites
          </h2>

          <Link href="/shop">
            <a className="text-base py-8 cursor-pointer text-black">See All</a>
          </Link>
        </div>
        <FreshProd />
      </section>
      <section className="py-4">
        <h2 className="text-2xl font-extrabold py-8">Recommended Products</h2>
        <FreshProd />
      </section>
    </main>
  );
}

As said before we will use all the data locally therefore we left all the data in FreshProd.js component as an object. All the images are also stored in images folder for simplicity. We will fetch data using an external APIs or maybe from firebase database later in another tutorial.


const freshProds = [
  {
    id: "1",
    src: "/images/100p.jpeg",
    name: "100 Plus",
    category: "Groceries",
  },
  {
    id: "2",
    src: "/images/Ajinomoto.jpeg",
    name: "Ajinomoto",
    category: "Groceries",
  },
  {
    id: "3",
    src: "/images/Almondnuts.jpg",
    name: "Almondnuts",
    category: "Groceries",
  }, 
];

Now, store this object in a map so we can display them on <Product /> component. For that we need to Destructuring Props.


function FreshProd() {

  return (
    <div>
      <div className="grid grid-cols-3">
        {freshProds?.map((freshprod) => (
          <Product
            key={freshprod.id}
            src={freshprod.src}
            name={freshprod.name}
            category={freshprod.category}
          />
        ))}
      </div>
    </div>
  );
}

export default FreshProd;

Up to this point, we are able to view all the products in Product component.


import React from "react";

import Image from "next/image";
function Product({ id, name, src, category }) {
  return (
    <div className="py-4">
      <div className="max-w-sm rounded overflow-hidden shadow-lg">
        <Image
          className="rounded-md"
          objectFit="fill"
          src={src}
          width={150}
          height={150}
        />
        <div className="px-6 py-4">
          <div className="font-bold text-xl mb-2">{name}</div>
          <p className="text-gray-700 text-base">{category}</p>
        </div>
      </div>
    </div>
  );
}

export default Product;

Now let’s try to write a function so that it display certain amount of products instead of displaying all the products on the screen. This is where we use Loadmore button and implement pagination on our app. In this case we want to display 6 products.


const [visible, setVisible] = useState(6);

  const showMoreItems = () => {
    setVisible((prevValue) => prevValue + 6);
  };

Lastly we slice the object, so in each time we press the button it will display 6 products on the screen. We use props to pass the data to Product component.


<div className="grid grid-cols-3">
   {freshProds?.slice(0, visible).map((freshprod) => (
      <Product
         key={freshprod.id}
         src={freshprod.src}
         name={freshprod.name}
         category={freshprod.category}
          />
     ))}
</div>

This is the button which is used to load more products on each click.


<div className=" flex flex-col  pt-8	">
    <button
      className=" content-between bg-transparent hover:bg-green-800 
      text-green-800 font-semibold hover:text-white py-2 px-4 border
      border-green-800 hover:border-transparent rounded"
      onClick={showMoreItems} >
          Load More
     </button>
</div>

Wrap Up

Thats it! Now we have implemented simple pagination or loadmore functionlity on our Next.js app project. We can improve this functionality and code but this is a good starting point.


Code

You can find the source code Github

How to Navigate Between Pages Using Next JS Links

How to Navigate Between Pages Using Next JS Links

Introduction


One of the very first reasons to get up early when you’re beachside is to see beautiful sunrise. Today I spent time on beach area aiming to complete this article I started last night. This is a short article where I wrote about Next.js navigation and its implementation. So without further ado let’s jump into the topic.

Websites and web applications generally have more than one pages. But you may wondering, how to achieve routing in Next.js so users able to navigate between the pages. In this article, we’ll explore how to navigate between the pages but before that, first let’s look into the brief introduction of Next.js.


What is Next.js ?


In our previous article we have discussed about Next.js and its cool features in more in-depth. Next.js is an open-source development framework built on top of React.js. It is React based framework having various functionalities to power up both server-side rendering and generating client side static websites.

Next.js gives you amazing developer experience with all the features it provides for any production ready application. Features such as hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching give developers a seamless development experience.

Now, let’s explore how to add more pages to our application and how to manage page routing in Next.js.


In this article, we will learn:

  • Setup project in Next.js
  • Create pages
  • Use Link component to enable client-side navigation between pages.

1. Setup project in Next.js

We start with initial setup of the Next.js project. If this is the first time you are trying to create a project in Next.js then refer Nextjs official website where you get an extensive knowledge on Nextjs and its core functionalities.

To create a new app simply write the following command create-next-app, which sets up everything automatically for you. To create a project, run:


npx create-next-app@latest
# or
yarn create next-app

After installation is completed:

  • Run npm run dev or yarn dev to start the development server on http://localhost:3000
  • Visit http://localhost:3000 on your browser to view your application

2. Create pages

In Next.js, usually we create separate folder directory called pages. This folder consists of all the pages for the application. Pages are associated with the routes based on their file name. For example:

  • pages/index.js is associated with the / route.

const Index = () => <h1>Home page!</h1>
export default Index;

  • pages/about.js is associated with the /about.js route.

export default function About() {
  return <h1>About</h1>
}

3. Link component

Now we use next/link to enable the redirection between pages. To link different pages, we use <a> HTML tag. Next.js uses Link Component from next/link to wrap the <a> tag. <Link> allows you to do client-side navigation to a different page in the application.


To use Nextjs <Link>

First, open pages/index.js, and import the Link component from next/link by adding this line at the top:


import Link from 'next/link'


export default function Home() {

return (

<div className="lg:inline-flex lg:flex-row lg:ml-auto lg:w-auto w-full 
          lg:items-center items-start  flex flex-col lg:h-auto mr-12">
    <Link href="/">
      <a className="navtext uppercase">Home</a>
    </Link>
    <Link href="/about">
      <a className="navtext uppercase">About</a>
    </Link>
    <Link href="/contact">
      <a className="navtext uppercase"> Contact</a>
    </Link>
</div>

  );
}

In this example we create about us page only for simplicity. Therefore, open pages/about.js  and start writing content. You can add rest of the pages later.


function about() {
  return (
    <div className="container mx-auto px-4 sm:px-12 py-12">
      <h1 className="text-xl font-medium">About</h1>
      <p className="text-md font-base py-12">
        is simply dummy text of the printing and typesetting industry. Lorem
        Ipsum has been the industry's standard dummy text ever since the 1500s,
        when an unknown printer took a galley of type and scrambled it to make a
        type specimen book. It has survived not only five centuries, but also
        the leap into electronic typesetting, remaining essentially unchanged.
        It was popularised in the 1960s with the release of Letraset sheets
        containing Lorem Ipsum passages, and more recently with desktop
        publishing software like Aldus PageMaker including versions of Lorem
        Ipsum.
      </p>
    </div>
  );
}

export default about;

Wrap Up

In this tutorial we learnt how to use Next.js link to navigate between different pages on the websites. Next.js comes with so many great features including Client-Side Navigation and Dynamic Navigation but in this example we have used client-side navigation using Link tag. Now linking pages in any Next.js website is easier than ever, Huge thanks to the Next.js team.

Demo


Full Code

You can get full code from my GitHub repository. Also this demo is deployed in Vercel. Have a look!

Top 11 Best VS Code Extensions you Need in 2022!

Top 11 Best VS Code Extensions you Need in 2022 website

Top Must Have Extensions For Your Next Project

Visual Studio Code is undoubtedly the most popular code editor today. It is lightweight code editor developed by Microsoft for Windows, Linux and macOS. It includes various features such as syntax highlighting, debugging, intelligent code completion, snippets, embedded Git, code refactoring and many more. VS Code provides better performance and stability compared to other code editors in the market.

Microsoft has huge market place for VS Code where developers able to get third party plugins and extensions, availing VS Code more rich and efficient. Today we are discussing top 11 plugins for VS Code which provides invaluable to the speed and quality to your projects.

In this guide, we’ll explore the following extensions.

  1. Git Lens
  2. Peacock
  3. Tailwind CSS IntelliSense
  4. Bracket Pair Colorizer
  5. ES7+ React/Redux/React-Native snippets
  6. Prettier – Code formatter
  7. Auto Rename Tag
  8. Live Share
  9. Vscode-Icons
  10. TODO Highlight
  11. Tabnine AI Autocomplete for Javascript, Python, Typescript, PHP, Go, Java, Ruby & more

1. Git Lens

  • Publishers: GitKraken
  • Installs: 12,650,938 installs
  • Version: 11.7.0, Last Updated 11/18/2021 Free

Overview

GitLens supercharges the Git capabilities. GitLens helps you to understand code better. This powerful and feature rich tool helps to quickly look into code changes such as who, why, and when a line or code block was changed. You are able to find code history to gain further insights as to how and why the code evolved. With this tools, you can effortlessly explore the history and evolution of a codebase.

Here are just some of the unique features GitLens provides,

image visualstudio marketplace
  • Authorship code lens showing the most recent commit and number of authors at the top of files and/or on code blocks
  • status bar blame annotation showing the commit and author who last modified the current line
  • Code changes — highlights any local (unpublished) changes or lines changed by the most recent commit
  • Heatmap — shows how recent and often lines were changed, relative to all the other changes in the file and to now (hot vs. cold)

2. Peacock

  • Publishers: Johnpapa
  • Installs: 1,449,402 installs
  • Version: 4.0.0, Last Updated 11/17/2021 Free

Overview

Developers love to open multiple windows of VS Code as they work on more than one projects at the same time. For example, both backend and front end project could be opened in two separate VS Code instances and developers might want move from one project to another. Using this extension developers able to change the color of each project windows, so that it can be quickly identify which project or repo they are working.

image marketplace.visualstudio

Installation and Configuration

  1. Create/Open a VSCode Workspace (Peacock only works in a Workspace)
  2. Press F1 to open the command palette
  3. Type Peacock
  4. Choose Peacock: Change to a favorite color
  5. Choose one of the pre-defined colors and see how it changes your editor

3. Tailwind CSS IntelliSense

  • Publishers: Tailwind Labs
  • Installs: 871,182 installs
  • Version: 0.7.6, Last Updated 01/17/2022 Free

Overview

TailwindCSS is a utility-first CSS framework that has been gaining huge attention among the web developers. If you love Tailwind CSS then this is a must have extension to have. It is a free extension, published by Tailwind Labs (bradlc). This extension provides autocomplete, syntax highlighting, and linting for Tailwind classes. With this extension, developers don’t need to memorize the exact spelling of all the utility classes or to spend the time typing them out.

Linting

Linting highlights errors and potential bugs in both your CSS and your markup. It is the process of checking the source code for Programmatic as well as Stylistic errors.

Autocomplete

Intelligent suggestions for class names, as well as CSS functions and directives.

Installation and Configuration

In order for the extension to activate you must have tailwindcss installed and a Tailwind config file named tailwind.config.js or tailwind.config.cjs in your workspace.


4. Bracket Pair Colorizer

  • Publishers: CoenraadS
  • Installs: 7,279,363 installs
  • Version: 1.0.62, Last Updated 12/13/2021 Free

Overview

As our functions get more complex, it becomes more challenging to keep track of opening and closing brackets such as parentheses and curly braces.

We can use a VS Code extension called Bracket Pair Colorizer to add color to each set of opening and closing brackets, making it easier to identify each set of brackets.

image dev.to

Installation and Configuration

Install Bracket Pair Colorizer latest version from VS code package. After installation if you want customization:

  • Open up Settings by clicking Code > Preferences > Settings.
  • Search colorizer
  • Click Edit in settings.json beneath the bracket-pair-colorizer: Colors.

5. ES7+ React/Redux/React-Native snippets

  • Publishers: dsznajder
  • Installs: 4,344,921 installs
  • Version: 4.1.0, Last Updated 1/20/2022 Free

Overview

If you are a true React JS developer then this is a must have snippet for you, because it simply does just right for you. This plugin provides you JavaScript and React/Redux snippets in ES7 with Babel plugin features for VS Code.

image geeksforgeeks

Here you can see couple of popular PrefixMethod example for React developers, and the full list can be seen from official Github page.

To make a new class component, simply run:

rcc→

rce→

rfce

To make a functional component, simply run:

import React from 'react';

function $1() {
  return <div>$0</div>;
}

export default $1;

Installation and Configuration

Launch Quick Open:

Paste the following command and press Enter:

ext install dsznajder.es7-react-js-snippets

6. Prettier – Code formatter

  • Publishers: Prettier
  • Installs: 18,020,985 installs
  • Version: 9.1.0, Last Updated 1/3/2022 Free

Overview

Developers have different opinions on how to format the code structure so it would be readable. Prettier was created as a means of alleviating this challenge and ensures one unified code format within the development team.

Prettier reformats your JavaScript code consistently so that it make easy to read and understand the code. This plugin helps to format spacing, variable declarations, semi-colons, trailing commas and much more.

You can configure Prettier to format your files when saving them or committing them to a version control system (e.g. Git, SVN). This way, you do not have to worry about your source code formatting and Prettier takes care about it.

image honeypot

Installation and Configuration

Install through VS Code extensions. Search for Prettier - Code formatter

Visual Studio Code Market Place: Prettier – Code formatter

You can also installed in VS Code: Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.

ext install esbenp.prettier-vscode

7. Auto Rename Tag

  • Publishers: Jun Han
  • Installs: 7,766,922 installs
  • Version: 0.1.9, Last Updated 10/12/2021 Free

Overview

Most of the tags in HTML/XML need a corresponding closing tag. When writing large applications which consists of thousands and sometime millions of lines of code, the corresponding closing tags might located at very bottom of the editor, where developers has to scroll hundreds and thousand of lines below. It is tedious if you want to rename the tags.

Auto Rename Tag provides us with a feature that when we change the starting tag it will automatically rename paired HTML/XML tag, same as Visual Studio IDE does, making the renaming of tags easier.

Installation and Configuration

You can simply install the plugin using VS code Extensions. After installation, Add entry into auto-rename-tag.activationOnLanguage to set the languages that the extension will be activated. By default, it is [“*”] and will be activated for all languages.

{
  "auto-rename-tag.activationOnLanguage": ["html", "xml", "php", "javascript"]
}

8. Live Share

  • Publishers: Microsoft
  • Installs: 7,397,050 installs
  • Version: 1.0.5273, Last Updated 1/20/2022 Free

Another great contribution by Microsoft. Live Share enables you to collaboratively edit and debug code with other developers in real time. Using this tools, pair programming has become more convenient, where developers can instantly and securely share the project with other developers.

Common features it includes, debugging sessionsterminal instanceslocalhost web appsvoice calls, and more!

It shares all of their editor context meaning, other developers do not worry about cloning any repos or SDKs installation for code review and debugging process.

Installation and Configuration

  1. If needed, install Visual Studio Code for Windows (7+), macOS (Sierra+), or Linux (details).
  2. Download and install the Visual Studio Live Share extension for Visual Studio Code.
    If you want to integrated voice calling, then install the VS Live Share Extension Pack, which includes both the Live Share and Live Share Audio extensions.
  3. Let Visual Studio Live Share to finish installing dependencies.
  4. Once complete, you’ll see Live Share appear in your status bar. You can now begin collaborating with others immediately!

Quickstart (Joining)

  1. Click the session URL the “host” sent you, which will open it up in a browser. When prompted, allow your browser to launch VS Code
  2. You’ll be asked to sign in the first time you share (using a GitHub or Microsoft account), which allows others to identity you when collaborating.
  3. That’s it! After you join, you’ll be immediately presented with the file that the “host” has open, and can see their cursor and any edits they make. Additionally, you start out “following” the host, so as they scroll or navigate between files, you’ll follow along with them. This makes it easy to orient yourself with the issue/question/task you’re about to start collaborating on.

9. Vscode-Icons

  • Publishers: VSCode Icons Team
  • Installs: 9,823,196 installs
  • Version: 11.8.0, Last Updated 12/4/2021 Free

Overview

Having descriptive icons help you differentiate between files and folders in the project. Having icons in your project make more interesting and attractive. Below diagram depict different between two VS Code tabs with One having icons, the other does not.

image logrocket

Installation and Configuration

To install the extension just execute the following command in the Command Palette of Visual Studio Code:

ext install vscode-icons

Once installed and after reloading vscode, you will be presented with a message to Activate the icons.

In case this doesn’t happen, navigate to:

  • Linux & Windows => File > Preferences > File Icon Theme > VSCode Icons.
  • MacOS => Code > Preferences > File Icon Theme > VSCode Icons.

10. TODO Highlight

  • Publishers: Wayou Liu
  • Installs: 2,270,992 installs
  • Version: 11.8.0, Last Updated 12/4/2021 Free

This plugin lets you to highlight TODO, FIXME and other annotations within your code. This is really a useful plugin for highlighting comments such as NOTE: , TODO: , DEBUG:. The customization settings are also quite extensive making it perfect for the developer, thus leading level up your comments on any project.

image visualstudio marketplace

Installation and Configuration

  • TODO:,FIXME: are built-in keywords.
  • You can override the look by customizing the setting.
  • To customize the keywords and other stuff,
  • command + ,
  • (Windows / Linux: File -> Preferences -> User Settings)
  • open the vscode file settings.json.

11. Tabnine AI Autocomplete for Javascript, Python, Typescript, PHP, Go, Java, Ruby & more

  • Publishers: TabNine
  • Installs: 3,112,708 installs
  • Version: 3.5.16, Last Updated 1/12/2022 Free

Overview

Tabnine is the AI code completion assistant already trusted by millions of developers to amplify coding accuracy and boost productivity. Whether you are a new dev or a seasoned pro, working solo or part of a team, Tabnine AI assistant will suggest team-tailored code completions in most popular coding languages and all your favorite IDEs.

Tabnine is powered by sophisticated machine learning models. It is trained on more than a billion lines of open-source code from GitHub.

Tabnine suggests and predicts code as you write. This powerful extension speed up your development, save you tons of time and cutting your coding time in half. Currently it support almost all the popular programming languages including Python, Javascript, Java and React.

Tabnine’s Team Learning Algorithm studies your team’s code, preferences, and patterns, continuously learning and adapting. Every interaction with a team member amplifies code completion accuracy.

Installation and Configuration

  • Press Cmd+P (mac) or Ctrl+P (Windows) in your Visual Studio Code, type ext install Tabnine.tabnine-vscode and press Enter
  • Click the Reload button in the extensions tab
  • The default behavior of Tabnine uses the Enter key to accept completions. If you would rather use the Enter key to start a new line, go to Settings → Editor: Accept Suggestion On Enter and turn it off.

Conclusion

In this article, we reviewed 11 VS Code extensions that can help to make you a better programmer and boost your productivity. There are many more other cool extensions that we need to explore in future, so If we have time then will definitely look into those extensions in the coming articles.

Build Responsive Mobile Navigation With NextJS and TailwindCSS

NextJS

Next.js is an open-source development framework built on top of React.js. It is React based framework which have various functionalities to power up both server-side rendering and generating client side static websites.

Next.js gives you the best developer experience with all the features it present for any production ready apps. Features such as hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching give developers a seamless development experience.


TailwindCSS

TailwindCSS is utility-based low level CSS framework intended to ease building web applications much faster and more efficiently. TailwindCSS is so popular nowadays, because it helps build websites without ever leaving your HTML files.

The purpose of this post is to show how easy and intuitive it can be to make a responsive navbar in NextJS with the help of TailwindCSS. So let’s begin. Before we start writing some code, we need to do some initial configuration for tailwind and Nextjs.

Setup and configuration

So, the first thing that we need is install NextJS with NextCli, in our case we prefer to use npm.

Start by creating a new Next.js project if you don’t have one set up already. The most common approach is to use Create Next App:


npx create-next-app -e with-tailwindcss responsive-navigation

After creating our boilerplate code, we proceed to install Tailwind and the dependencies:

Setting up Tailwind CSS

To begin with, we install Tailwind. Tailwind CSS requires Node.js so we need to have compatible node version first. After that we can install Tailwind via npm.

Note: Tailwind CSS requires Node.js 12.13.0 or higher.

Install Tailwind via npm

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

Create your configuration files

To generate our tailwind.config.js and postcss.config.js files:

npx tailwindcss init -p

This will create a minimal tailwind.config.js file at the root of your project. It will also create a postcss.config.js file that includes tailwindCSS and autoprefixer already configured:

Now we need to create Navbar.js in components folder and then call this file directly in Index.js.

import { Navbar } from "../components/Navbar";

export default function Home() {
  return (
    <div>
      <Navbar />
      <div>Responsive Navigations</div>
    </div>
  );
}

Next create navigation bar in the main header. In addition we will proceed to add the hamburger menu that will be responsive for mobile and desktop screens.

import Link from 'next/link';

export const Navbar = () => {
  return (
    <>
      <nav className='flex items-center flex-wrap bg-green-400 p-3 '>
        <Link href='/'>
          <a className='inline-flex items-center p-2 mr-4 '>
            <svg
              viewBox='0 0 24 24'
              xmlns='http://www.w3.org/2000/svg'
              className='fill-current text-white h-8 w-8 mr-2'
            >
              <path d='M12.001 4.8c-3.2 0-5.2 1.6-6 4.8 1.2-1.6 2.6-2.2 4.2-1.8.913.228 1.565.89 2.288 1.624C13.666 10.618 15.027 12 18.001 12c3.2 0 5.2-1.6 6-4.8-1.2 1.6-2.6 2.2-4.2 1.8-.913-.228-1.565-.89-2.288-1.624C16.337 6.182 14.976 4.8 12.001 4.8zm-6 7.2c-3.2 0-5.2 1.6-6 4.8 1.2-1.6 2.6-2.2 4.2-1.8.913.228 1.565.89 2.288 1.624 1.177 1.194 2.538 2.576 5.512 2.576 3.2 0 5.2-1.6 6-4.8-1.2 1.6-2.6 2.2-4.2 1.8-.913-.228-1.565-.89-2.288-1.624C10.337 13.382 8.976 12 6.001 12z' />
            </svg>
            <span className='text-xl text-white font-bold uppercase tracking-wide'>
              Responsive Navigation
            </span>
          </a>
        </Link>
        <button className=' inline-flex p-3 hover:bg-gray-900 rounded lg:hidden text-white ml-auto hover:text-white outline-none'>
          <svg
            className='w-6 h-6'
            fill='none'
            stroke='currentColor'
            viewBox='0 0 24 24'
            xmlns='http://www.w3.org/2000/svg'
          >
            <path
              strokeLinecap='round'
              strokeLinejoin='round'
              strokeWidth={2}
              d='M4 6h16M4 12h16M4 18h16'
            />
          </svg>
        </button>
        <div className='hidden w-full lg:inline-flex lg:flex-grow lg:w-auto'>
          <div className='lg:inline-flex lg:flex-row lg:ml-auto lg:w-auto w-full lg:items-center items-start  flex flex-col lg:h-auto'>
            <Link href='/'>
              <a className='lg:inline-flex lg:w-auto w-full px-3 py-2 rounded text-white font-bold items-center justify-center hover:bg-gray-600 hover:text-white '>
                Home
              </a>
            </Link>
            <Link href='/'>
              <a className='lg:inline-flex lg:w-auto w-full px-3 py-2 rounded text-white font-bold items-center justify-center hover:bg-gray-600 hover:text-white'>
                Services
              </a>
            </Link>
            <Link href='/'>
              <a className='lg:inline-flex lg:w-auto w-full px-3 py-2 rounded text-white font-bold items-center justify-center hover:bg-gray-600 hover:text-white'>
                About us
              </a>
            </Link>
            <Link href='/'>
              <a className='lg:inline-flex lg:w-auto w-full px-3 py-2 rounded text-white font-bold items-center justify-center hover:bg-gray-600 hover:text-white'>
                Contact
              </a>
            </Link>
          </div>
        </div>
      </nav>
    </>
  );
};

Lastly we need a function that hide and show the menu as we click in the hamburger menu. For this we create a state using the useState hook and a function for the button to click the button. We need to call this function when we click the button on the menu.

There is break points which lets, navigation bar to change based on the break points. When it hit small screen sizes such as mobile views, the hamburger menu will be activated. However when we view on large screens the default inline navigation bar activates.

const [active, setActive] = useState(false);

  const handleClick = () => {
    setActive(!active);
  };
<button
    className=' inline-flex p-3 hover:bg-green-600 rounded lg:hidden text-white ml-auto hover:text-white outline-none'
    onClick={handleClick}
  >
    <svg
      className='w-6 h-6'
      fill='none'
      stroke='currentColor'
      viewBox='0 0 24 24'
      xmlns='http://www.w3.org/2000/svg'
    >
      <path
        strokeLinecap='round'
        strokeLinejoin='round'
        strokeWidth={2}
        d='M4 6h16M4 12h16M4 18h16'
      />
    </svg>
</button>

Conclusion

That it’s all. Now we have created a simple responsive responsive menu navigation using NextJS and TailwindCSS.

If you want to learn more on TailwindCSS and NextJS please follow these links of their official sites. Both these technologies are powerful frameworks with great documentation that will allow us to learn more build fun products.

Code Github

Add Tailwind CSS to Existing React JS Project

Sandbanks are everywhere here in Maldives. Today, I went to a sandbank called Vagaath gale hutta (I believe that is the correct location), which is roughly 5 miles north west of Dhevvadhoo. During the trip I took time to write this tutorial.

So without further ado let’s begin…

Front-end technologies are constantly evolving. Some technologies are becoming incredibly popular among the developers while others get less attraction. When it comes to front-end development, now React JS has become number one choice for most of the developers.

When it comes to CSS frameworks, TailwindCSS started to get more stars on Github meaning developers love to use TailwindCSS over other CSS technologies.


React JS


React JS is a JavaScript library developed by Facebook. React JS is efficient, declarative and flexible open-source JavaScript library which lets developers to build scalable frontend web applications much faster and easier. It offers tons of benefits. Compare to other front-end frameworks, React JS is easy to learn, SEO-friendly, helps to build rich user interfaces, able to write custom components and much more.


TailwindCSS


TailwindCSS is utility-based low level CSS framework intended to ease building web applications much faster and efficiently. TailwindCSS helps to build websites without ever leaving your HTML files.

In this tutorial, you will learn how to add tailwindCSS to an existing React JS application. So without further ado let’s create a react app by running the following command.


npx create-react-app react-tailwind
cd react-tailwind

Go to directory of your my-app and run the following command.


npm i tailwindcss postcss-cli autoprefixer -D

Enter the following command to create the default configuration. This will create a tailwind.js file in the current directory.


npx tailwind init tailwind.js --full

Now, we need to create postcss.config.js file. For that simply run the command below. PostCSS is a tool for transforming styles with JS plugins.


touch postcss.config.js

const tailwindcss = require('tailwindcss');
module.exports = {
    plugins: [
        tailwindcss('./tailwind.js'),
        require('autoprefixer')
    ],
};

Create an assets directory in the src folder.


mkdir ./src/assets

Then create a file called tailwind.css in ./src/assets.


touch ./src/assets/tailwind.css

Now open tailwind.css and then import the following tailwind files as shown.


@import "tailwindcss/base";

@import "tailwindcss/components";

@import "tailwindcss/utilities";

Now it is time to modify package.json file just little bit. Simply add the following lines in the scripts tags.


"scripts": {
    "start": "yarn watch:css && react-scripts start",
    "build": "yarn build:css && react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "build:css": "postcss src/assets/tailwind.css -o src/assets/main.css",
    "watch:css": "postcss src/assets/tailwind.css -o src/assets/main.css"
  },

Lastly import the file ./src/assets/main.css in the App.js file (or the root file of the application).


import React from "react";
import ReactDOM from "react-dom";
import './assets/main.css';
ReactDOM.render(<App />, document.getElementById("root"));

Now run the development server. Simply run:

npm start

Thats all! Now you can able to use Tailwind classes in your React JS application.

Code: Github