Javascript Archives - Coding is Love https://codingislove.com/tag/javascript/ Sat, 15 Feb 2025 16:16:57 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.5 https://codingislove.com/wp-content/uploads/2015/12/codinglovenew-150x150.png Javascript Archives - Coding is Love https://codingislove.com/tag/javascript/ 32 32 Ultimate Guide: Build A Mobile E-commerce App With React Native And Medusa.js https://codingislove.com/medusa-mobile-react-native/ https://codingislove.com/medusa-mobile-react-native/#respond Sat, 15 Feb 2025 16:13:47 +0000 https://codingislove.com/?p=4443 Looking to build a mobile app with Medusa.js? This comprehensive guide walks you through creating a React Native Medusa mobile app from scratch. Whether you’re starting a new project…

The post Ultimate Guide: Build A Mobile E-commerce App With React Native And Medusa.js appeared first on Coding is Love.

]]>
Looking to build a mobile app with Medusa.js? This comprehensive guide walks you through creating a React Native Medusa mobile app from scratch. Whether you’re starting a new project or looking for a React Native starter Medusa template, you’ll learn how to build a production-ready mobile e-commerce solution.

What is Medusa?

Medusa is an open-source headless commerce engine that enables developers to create unique and scalable e-commerce experiences. Unlike traditional e-commerce platforms, Medusa offers:

  • Headless Architecture: Complete freedom in frontend implementation
  • Extensible Core: Plugin system for custom functionality
  • Developer-First: Built with TypeScript and modern development practices
  • Multi-Region Support: Built-in multi-currency support based on region
  • Order Management: Comprehensive order lifecycle handling
  • Inventory Management: Built-in inventory and variant management
  • Modular architecture

Why React Native?

React Native is a framework for building native mobile applications using React:

  • Native Performance: Direct access to native platform capabilities
  • Code Reusability: Share logic between iOS and Android
  • Large Ecosystem: Extensive library of third-party packages
  • Hot Reload: Fast development with instant feedback
  • Strong Community: Active development and community support

Using React Native with Medusa

Combining React Native and Medusa.js creates powerful mobile e-commerce possibilities:

  • Native Mobile Experience: Build a React Native Medusa app with native UI components
  • Mobile-First Features: Leverage device capabilities like push notifications
  • Offline Support: Implement AsyncStorage for cart and user data
  • Performance Optimization: Native rendering for smooth product browsing
  • Cross-platform support: Build an Android and iOS e-commerce mobile app using a single code base

Introducing Medusa Mobile

Medusa Mobile is a complete React Native Medusa starter. It is not just a starter, it comes with 90% of the functionality that you need for a production-ready app.

Features of Medusa Mobile:

  • 🛍️ Product browsing with infinite scroll
  • 👤 User authentication and profile management
  • 🔍 Categories and collections
  • 🛒 Cart management
  • 🏃‍♂️ Guest checkout
  • 📦 Order tracking
  • 🎨 Multiple themes with dark mode

Setting up Medusa Backend

Before running the mobile app, you need a Medusa backend. Set it up in a few steps by following the official docs – Install Medusa backend application

Setting up Medusa Mobile

Now let’s set up the React Native Medusa mobile app

📋 Prerequisites

Before you begin, ensure you have:

Step 1: Environment Setup

  1. Clone the repository:
git clone [email protected]:bloomsynth/medusa-mobile-react-native.git medusa-mobile
cd medusa-mobile
  1. Install dependencies:
npm install
  1. Configure environment variables:
cp .env.template .env

Edit .env with your Medusa backend URL and publishable API key.

NOTE: Update the MEDUSA_BACKEND_URL in your .env file. If you set the URL as localhost, then the Android emulator will not be able to connect to the server. Use your local IP address instead. example: http://192.168.1.100:9000 Run ipconfig to get your local IP address.

Step 2: Start Metro Server

npm start

Step 3: Run the Application

For Android:

npm run android

For iOS: Install dependencies for iOS:

npx pod-install ios

Run the application:

npm run ios

📱 Expo Usage

This project uses React Native CLI to ensure maximum flexibility for all developers. However, Expo users are more than welcome! You can easily add Expo support with a single command.

Learn more about migrating to Expo CLI

📁 Project Structure

app/
├── screens/       # Screen components
├── components/    # Reusable UI components
├── data/          # Data context providers
├── styles/        # Theme and style utilities
├── utils/         # Helper functions
└── api/           # API client configuration

📖 Developer Guide

Here’s the documentation for managing the core functionality of the app.

🛒 Cart Management

The cart functionality is provided through the useCart hook, which gives you access to cart operations and state.

Basic Usage

import { useCart } from '@data/cart-context';

function MyComponent() {
  const { 
    cart,                // Current cart state
    addToCart,          // Add items to cart
    updateLineItem,     // Update item quantity
    removeLineItem,     // Remove item from cart
    applyPromoCode,     // Apply discount code
    removePromoCode,    // Remove discount code
    setShippingMethod   // Set shipping option
  } = useCart();
}

Working with Cart Items

  1. Add a product to the cart:
const { addToCart } = useCart();

// Quantity is required when adding items
await addToCart(variantId, 1); // Add one item
await addToCart(variantId, 3); // Add three items
  1. Update item quantity:
const { updateLineItem } = useCart();

// Update to specific quantity
await updateLineItem(lineItemId, 2);

// Remove item by setting quantity to 0
await updateLineItem(lineItemId, 0);

Managing Promotions

const { applyPromoCode, removePromoCode } = useCart();

// Apply a promotion code
const success = await applyPromoCode('SUMMER2024');

// Remove a promotion code
await removePromoCode('SUMMER2024');

Shipping Methods

const { setShippingMethod } = useCart();

// Set shipping method
await setShippingMethod(shippingMethodId);

Accessing Cart Data

const { cart } = useCart();

// Get cart items
const items = cart.items;

// Get cart totals
const {
  subtotal,
  tax_total,
  shipping_total,
  discount_total,
  total
} = cart;

// Check applied discounts
const appliedPromotions = cart.promotions;

// Get selected shipping method
const currentShipping = cart.shipping_methods?.[0];

Cart Lifecycle

The cart system handles various states and transitions:

  1. Cart Creation:
const { cart } = useCart();

// Cart is automatically created when needed
// You don't need to explicitly create a cart
  1. Guest to Customer Cart Transfer:
// When a guest user logs in, their existing cart is 
// automatically associated with their customer account
// This is handled by the CartProvider and CustomerProvider

import { useCustomer } from '@data/customer-context';
import { useCart } from '@data/cart-context';

function CheckoutFlow() {
  const { customer } = useCustomer();
  const { cart } = useCart();
  
  // Cart remains the same, only the customer_id is updated
}
  1. Cart update on region change:
import { useRegion } from '@data/region-context';
import { useCart } from '@data/cart-context';

function MyComponent() {
  const { region } = useRegion();
  const { cart } = useCart();

  // Cart automatically updates when region changes
  // Product prices will be updated based on the region
  console.log(cart.region_id); // Current region ID
  console.log(cart.currency_code); // Region's currency
}

🌍 Region Management

The region functionality is provided through the useRegion hook, which handles region selection and persistence.

Basic Usage

import { useRegion } from '@data/region-context';

function MyComponent() {
  const {
    region,             // Current selected region
    setRegion,          // Update region state
  } = useRegion();
}

Working with Regions

  1. Access current region:
const { region } = useRegion();

// Get region details (if region is loaded)
const {
  id,
  name,
  currency_code,
  countries
} = region || {};
  1. Change region:
const { setRegion } = useRegion();

// Fetch region data first
const { region: newRegion } = await apiClient.store.region.retrieve(regionId);

// Update region
setRegion(newRegion);
// This will:
// - Persist region selection
// - Update cart region automatically
// - Trigger price recalculations

Region Selection UI

The app provides a built-in region selector modal:

import { useNavigation } from '@react-navigation/native';

function MyComponent() {
  const navigation = useNavigation();
  
  // Open region selector modal
  const openRegionSelect = () => {
    navigation.navigate('RegionSelect');
  };
}

Working with Countries

The app provides a dedicated hook for accessing region countries:

import { useCountries } from '@data/region-context';

function AddressForm() {
  const countries = useCountries();
  
  // Format countries for picker/selector
  const countryOptions = countries?.map(country => ({
    label: country.display_name,
    value: country.iso_2
  }));
}

Region Persistence

Region selection is automatically persisted using AsyncStorage:

  • On first load, defaults to the first available region
  • On subsequent loads, restores the previously selected region
  • Region ID is stored under the ‘region_id’ key

👤 Customer Management

The customer functionality is provided through the useCustomer hook, which handles authentication and customer data management.

Basic Usage

import { useCustomer } from '@data/customer-context';

function MyComponent() {
  const {
    customer,           // Current customer data
    login,             // Login with email/password
    logout,            // Logout current customer
    register,          // Register new customer
    refreshCustomer,   // Refresh customer data
    updateCustomer     // Update customer details
  } = useCustomer();
}

Authentication

  1. Login:
const { login } = useCustomer();

try {
  await login(email, password);
  // On successful login:
  // - JWT token is stored in AsyncStorage
  // - Customer data is fetched
  // - Cart is associated with customer
} catch (error) {
  // Handle login error
}
  1. Register new customer:
const { register } = useCustomer();

try {
  await register(
    email,
    password,
    firstName,
    lastName
  );
  // Registration automatically logs in the customer
} catch (error) {
  // Handle registration error
}
  1. Logout:
const { logout } = useCustomer();

await logout();
// This will:
// - Clear the stored JWT token
// - Reset customer data
// - Reset cart

Managing Customer Data

  1. Access customer information:
import { useLoggedIn } from '@data/hooks';

function MyComponent() {
  const { customer } = useCustomer();
  const isLoggedIn = useLoggedIn();

  // Access customer details
  const {
    email,
    first_name,
    last_name,
    phone,
    billing_address,
    shipping_addresses
  } = customer || {};
}
  1. Update customer details:
const { updateCustomer } = useCustomer();

// Update customer information
await updateCustomer({
  first_name: "John",
  last_name: "Doe",
  phone: "+1234567890"
});
  1. Refresh customer data:
const { refreshCustomer } = useCustomer();

// Fetch latest customer data from server
await refreshCustomer();

Session Management

The customer session is automatically managed:

  • JWT token is stored in AsyncStorage under ‘auth_token’
  • Session is restored on app launch
  • Token is automatically attached to API requests
  • Session is cleared on logout

🎨 Theme Management

The app includes a flexible theming system with built-in light/dark mode support and multiple color schemes.

Basic Usage

import { useColors, useTheme, useThemeName, useColorScheme } from '@styles/hooks';

function MyComponent() {
  const colors = useColors();          // Get current theme colors
  const themeName = useThemeName();    // Get current theme name
  const { colorScheme } = useColorScheme(); // Get 'light' or 'dark'

  // Access theme colors
  const {
    primary,            // Brand/accent color
    background,         // Main background
    backgroundSecondary,// Secondary/card background
    content,           // Main text color
    contentSecondary   // Secondary text color
  } = colors;
}

Setting Default Theme

// In app.tsx, set your preferred theme name in ThemeProvider
<ThemeProvider name="default">
  {/* ... other providers */}
</ThemeProvider>

Available theme names:

  • “default” (Purple accent)
  • “vintage” (Warm red accent)
  • “funky” (Teal accent)
  • “eco” (Green accent)

Changing Themes

import { useTheme } from '@styles/hooks';

function ThemeSwitcher() {
  const { setThemeName } = useTheme();
  
  // Switch to a different theme
  const switchTheme = (name: string) => {
    setThemeName(name); // 'default' | 'vintage' | 'funky' | 'eco'
  };
}

System Dark Mode

The theme system automatically responds to system dark mode changes through NativeWind’s useColorScheme hook. Each theme includes both light and dark variants that are automatically applied based on the system setting.

Styling Components

The app uses NativeWind (TailwindCSS) for styling. Theme colors are available as Tailwind classes:

function ThemedButton() {
  return (
    <TouchableOpacity className="bg-primary"> // Theme primary color
      <Text className="text-content font-bold"> // Theme content color
        Click Me
      </Text>
    </TouchableOpacity>
  );
}

🪝 Useful Hooks

The app provides additional hooks for common functionality:

import { 
  useProductQuantity,
  useVariantQuantity,
  useCartQuantity,
  useCurrentCheckoutStep,
  useActivePaymentSession,
  useLoggedIn,
  useCountries
} from '@data/hooks';

// Get quantity of a specific product in cart
const quantity = useProductQuantity(productId);

// Get quantity of a specific variant in cart
const variantQuantity = useVariantQuantity(variantId);

// Get total number of items in cart
const cartQuantity = useCartQuantity();

// Get current checkout step
const checkoutStep = useCurrentCheckoutStep(); 
// Returns: 'address' | 'delivery' | 'payment' | 'review'

// Get active payment session in checkout
const paymentSession = useActivePaymentSession();

// Check if user is logged in
const isLoggedIn = useLoggedIn();

// Get formatted list of countries for current region
const countries = useCountries();
// Returns: Array<{ label: string, value: string }>

Read the detailed documentation in the official repo of Medusa Mobile

Next Steps

Your Medusa mobile app is now running! Here’s what to do next:

Customize Your App

  • Select one theme from the built-in themes, customize one of them, or build a new theme config to match your app requirement.
  • Modify UI as needed. You have access to full source code andthe ability to change anything.
  • Add custom features using Medusa’s API

Production Release

Follow React Native’s Release Guide for Android and iOS

Publishing to Google Play Store

Publishing to iOS App Store

Wrapping up

Start building your mobile commerce experience with React Native and Medusa today! Check out the GitHub repository of Medusa Mobile for the complete source code.

The post Ultimate Guide: Build A Mobile E-commerce App With React Native And Medusa.js appeared first on Coding is Love.

]]>
https://codingislove.com/medusa-mobile-react-native/feed/ 0 4443
Amazing AI slider created using javascript animations https://codingislove.com/amazing-ai-slider/ https://codingislove.com/amazing-ai-slider/#respond Mon, 10 Jul 2023 18:22:18 +0000 https://codingislove.com/?p=4362 Check out this interesting animation made with GSAP (Green Sock animation platform). You can tap the slider and change the value but the AI robot…

The post Amazing AI slider created using javascript animations appeared first on Coding is Love.

]]>
Check out this interesting animation made with GSAP (Green Sock animation platform). You can tap the slider and change the value but the AI robot will change it back to 11 again.

This is a fun effect created to showcase the power of Javascript animations.

AI slider demo

Live demo and Full source code

See the Pen AI Slider by Chris Gannon (@chrisgannon) on CodePen.

The post Amazing AI slider created using javascript animations appeared first on Coding is Love.

]]>
https://codingislove.com/amazing-ai-slider/feed/ 0 4362
Free avatar library for developers and designers | DiceBear https://codingislove.com/free-avatar-library-developers-designers/ https://codingislove.com/free-avatar-library-developers-designers/#respond Sun, 09 Jul 2023 12:58:30 +0000 https://codingislove.com/?p=4351 Avatars are needed in almost every app. Be it as a placeholder for profile photos or as a full-fledged avatar system in your app. Let’s…

The post Free avatar library for developers and designers | DiceBear appeared first on Coding is Love.

]]>
Avatars are needed in almost every app. Be it as a placeholder for profile photos or as a full-fledged avatar system in your app. Let’s see how to implement avatars for an app using DiceBear

Example avatars

DiceBear

DiceBear is an avatar library for designers and developers. Create avatars for your profiles, designs, websites, or apps. Piece by piece or based on a seed.

Features

  • More than 25 avatar styles!
  • Fully customizable!
  • Free and fast HTTP API!

Examples

Avataaars

Avataaars Neutral

Bottts

Micah

How to use it?

Are you a designer and need avatars for your design? Then check out their Figma Plugin and Editor. As a developer, you could take a look at the HTTP API, the CLI, the JS library or the Playground. Which is more appropriate for you, depends on the programming language and environment you are using.

In a JavaScript environment, you could use the JS library or the HTTP API if the JS library is too large for you. In other environments, you might be interested in the HTTP API or the CLI if you are concerned about the stability or latency of the HTTP API.

The CLI is always a good choice for automation or if you want to create a large number of avatars in different image formats.

How does it work?

The avatars are created in SVG format. This allows to generate avatars dynamically without much computing power. In most cases, various SVG elements such as hair, eyes, ears, etc. are selected from a set and combined to create a character/avatar.

XorShift32 is used as the algorithm for the PRNG. It is important to note that the PNGR does not attempt to be cryptographically secure.

Usage

HTTP API:

https://api.dicebear.com/6.x/adventurer/svg
<img
  src="https://api.dicebear.com/6.x/adventurer/svg"
  alt="avatar"
/>

JS-Library:

First install the required packages via npm:

npm install @dicebear/core @dicebear/collection --save

Then you can create this avatar as follows:

import { createAvatar } from '@dicebear/core';
import { adventurer } from '@dicebear/collection';

const avatar = createAvatar(adventurer, {
  // ... options
});

const svg = avatar.toString();

CLI:

First install the CLI package via npm:

npm install --global dicebear

Then you can create this avatar as follows:

dicebear adventurer

Get a specific avatar

If you want to get a specific avatar using a name then you can use the seed option

Example:

https://api.dicebear.com/6.x/avataaars/svg?seed=Buster

Output:

avatar sample

Conclusion

This is a very useful library for generating avatars for your next project. Head over to their playground for exploring further

The post Free avatar library for developers and designers | DiceBear appeared first on Coding is Love.

]]>
https://codingislove.com/free-avatar-library-developers-designers/feed/ 0 4351
How to create a collapsible in React easily https://codingislove.com/create-collapsible-react/ https://codingislove.com/create-collapsible-react/#respond Thu, 06 Jul 2023 18:31:02 +0000 https://codingislove.com/?p=4319 Collapsible that reveals or hides contest with an animation is a very common pattern used in web. Let’s see how to create a collapsible that…

The post How to create a collapsible in React easily appeared first on Coding is Love.

]]>
Collapsible that reveals or hides contest with an animation is a very common pattern used in web. Let’s see how to create a collapsible that opens on click easily in React

collapsible demo in react

Collapsible using auto-animate

AutoAnimate is a zero-config, drop-in animation utility that adds smooth transitions to your web app. You can use it with React, Solid, Vue, Svelte, or any other JavaScript application.

In this blog post, we’ll look at how to use it in ReactJs

Installation

Install using your package manager of choice to add @formkit/auto-animate to your project:

Yarn

yarn add @formkit/auto-animate

NPM

npm install @formkit/auto-animate

Usage

Using auto-animate to create a collapsible or accordion is very easy. All you need to do is use the useAutoAnimate hook and pass the return value to any list container. Once this is done, any child element that is removed from the div will be auto-animated!

Here’s some example code:

import { useAutoAnimate } from '@formkit/auto-animate/react'

function MyList () {
  const [animationParent] = useAutoAnimate()
  return (
    &lt;div ref={animationParent}>
      {/* 🪄 Magic animations for your child elements */}
    &lt;/div>
  )
}

Working demo

I’ve created a working demo in code sandbox to show how it works live. Here’s the code and the demo embedded below.

import "./styles.css";
import { useState, useRef, useEffect } from "react";
import autoAnimate from "@formkit/auto-animate";

export default function App() {
  const [show, setShow] = useState(false);
  const parent = useRef(null);

  useEffect(() => {
    parent.current && autoAnimate(parent.current);
  }, [parent]);

  const reveal = () => setShow(!show);
  return (
    <div className="container" ref={parent} onClick={reveal}>
      <strong className="dropdown-label">Click me to open!</strong>
      {show && (
        <p className="dropdown-content">
          Sea of Tranquility a mote of dust suspended in a sunbeam hundreds of
          thousands concept of the number one realm of the galaxies radio
          telescope. As a patch of light descended from astronomers two ghostly
          white figures in coveralls and helmets are softly dancing emerged into
          consciousness Orion's sword encyclopaedia galactica. Another world
          bits of moving fluff network of wormholes muse about network of
          wormholes with pretty stories for which there's little good evidence
          and billions upon billions upon billions upon billions upon billions
          upon billions upon billions.
        </p>
      )}
    </div>
  );
}

Also, Read How to animate list reordering with React easily

The post How to create a collapsible in React easily appeared first on Coding is Love.

]]>
https://codingislove.com/create-collapsible-react/feed/ 0 4319
How to access Tailwind config from JS? https://codingislove.com/access-tailwind-config-js/ https://codingislove.com/access-tailwind-config-js/#respond Sun, 02 Jul 2023 16:42:05 +0000 https://codingislove.com/?p=4297 We might need to access tailwind configuration in javascript sometimes. Let’s say we want to use one of our primary colors in a place where…

The post How to access Tailwind config from JS? appeared first on Coding is Love.

]]>
We might need to access tailwind configuration in javascript sometimes. Let’s say we want to use one of our primary colors in a place where CSS classes wouldn’t work, Then we need to reference the Tailwind color from Javascript. Here’s how to do it.

tailwind config

import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from './tailwind.config.js'

const {theme} = resolveConfig(tailwindConfig)

const color = theme.colors.blue[500]

Practical usage

The above snippet works for referencing any value from Tailwind config but it doesn’t make sense to write all those lines of code in every file that we want to use it in.

We can solve this by writing the above snippet only once and exporting it for usage everywhere.

import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from './tailwind.config.js'

const {theme} = resolveConfig(tailwindConfig)

export default theme;

Then import it wherever needed

import theme from './theme'; //Update the path as needed

const color = theme.colors.blue[500]

The post How to access Tailwind config from JS? appeared first on Coding is Love.

]]>
https://codingislove.com/access-tailwind-config-js/feed/ 0 4297
How to remove background from an image using Javascript? https://codingislove.com/remove-background-from-image-javascript/ https://codingislove.com/remove-background-from-image-javascript/#comments Sat, 01 Jul 2023 18:28:53 +0000 https://codingislove.com/?p=4289 Removing background from an Image is something we need quite often. We’ll be searching for background removal tools. Here’s how to remove background programmatically using…

The post How to remove background from an image using Javascript? appeared first on Coding is Love.

]]>
Removing background from an Image is something we need quite often. We’ll be searching for background removal tools. Here’s how to remove background programmatically using Javascript.

Remove background images using Javascript

Introducing background-removal-js

Remove backgrounds from images directly in the browser environment with ease and no additional costs or privacy concerns.

Overview

@imgly/background-removal is a powerful npm package that allows developers to seamlessly remove the background from images directly in the browser. With its unique features and capabilities, this package offers an innovative and cost-effective solution for background removal tasks without compromising data privacy.

Key features

The key features of @imgly/background-removal are:

  • In-Browser Background Removal: Our one-of-a-kind solution performs the entire background removal process directly in the user’s browser, eliminating the need for additional server costs. By leveraging the computing power of the local device, users can enjoy a fast and efficient background removal process.
  • Data Protection: As @imgly/background-removal runs entirely in the browser, users can have peace of mind knowing that their images and sensitive information remain secure within their own devices. With no data transfers to external servers, data privacy concerns are effectively mitigated.
  • Seamless Integration with IMG.LY’s CE.SDK@imgly/background-removal provides seamless integration with IMG.LY’s CE.SDK, allowing developers to easily incorporate powerful in-browser image matting and background removal capabilities into their projects.

The Neural Network (ONNX model) and WASM files used by @imgly/background-removal are hosted on UNPKG, making it readily available for download to all users of the library. See the section Custom Asset Serving if you want to host data on your own servers.

Installation

You can install @imgly/background-removal via npm or yarn. Use the following commands to install the package:

npm install @imgly/background-removal

Usage

import imglyRemoveBackground from "@imgly/background-removal"

let image_src: ImageData | ArrayBuffer | Uint8Array | Blob | URL | string = ...;

imglyRemoveBackground(image_src).then((blob: Blob) => {
  // The result is a blob encoded as PNG. It can be converted to an URL to be used as HTMLImage.src
  const url = URL.createObjectURL(blob);
})

Note: On the first run the wasm and onnx model files are fetched. This might, depending on the bandwidth, take time. Therefore, the first run takes proportionally longer than each consecutive run. Also, all files are cached by the browser and an additional model cache.

Advanced Configuration

The library does not need any configuration to get started. However, there are optional parameters that influence the behavior and give more control over the library.

type Config = {
  publicPath: string; // The public path used for model and wasm files
  debug: bool; // enable or disable useful console.log outputs
  proxyToWorker: bool; // Whether to proxy the calculations to a web worker. (Default true)
  model: 'small' | 'medium'; // The model to use. (Default "medium")
};

Download Size vs Quality

The onnx model is shipped in various sizes and needs.

  • small (~40 MB) is the smallest model and is in most cases working fine but sometimes shows some artifacts. It’s a quantized model.
  • medium (~80MB) is the default model.

Download Progress Monitoring

On the first run, the necessary data will be fetched and stored in the browser cache. Since the download might take some time, you have the option to tap into the download progress.

let config: Config = {
  progress: (key, current, total) => {
    console.log(`Downloading ${key}: ${(current} of ${total}`);
  }
}

Who is it for?

@imgly/background-removal is ideal for developers and projects that require efficient and cost-effective background removal directly in the browser. It caters to a wide range of use cases, including but not limited to:

  • E-commerce applications that need to remove backgrounds from product images in real time.
  • Image editing applications that require background removal capabilities for enhancing user experience.
  • Web-based graphic design tools that aim to simplify the creative process with in-browser background removal.

Whether you are a professional developer or a hobbyist, @imgly/background-removal empowers you to deliver impressive applications and services with ease.

Demo of image with background removed

Live Demo

A live demo of the background removal tool in Javascript can be explored here

The post How to remove background from an image using Javascript? appeared first on Coding is Love.

]]>
https://codingislove.com/remove-background-from-image-javascript/feed/ 1 4289
How to copy text to the clipboard using Javascript? https://codingislove.com/copy-text-clipboard-javascript/ https://codingislove.com/copy-text-clipboard-javascript/#respond Wed, 28 Jun 2023 17:21:08 +0000 https://codingislove.com/?p=4268 Allowing a user to copy text by clicking a button is a common pattern in websites. Let’s see how to copy text to clipboard using…

The post How to copy text to the clipboard using Javascript? appeared first on Coding is Love.

]]>
Allowing a user to copy text by clicking a button is a common pattern in websites. Let’s see how to copy text to clipboard using Javascript

Copy using the navigator.clipboard API

Here’s how to copy or set some text to the clipboard:

navigator.clipboard.writeText("Some text to be copied");

Full source code

Here’s the full source code and live demo

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="icon"
      href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎉</text></svg>"
    />
    <title>How to copy text</title>
  </head>
  <body>
    <h1>How to copy text</h1>
    <textarea rows="3">
Some sample text for you to copy. Feel free to edit this.</textarea
    >
    <button type="button">Copy</button>
  </body>
</html>

JS:

const textarea = document.querySelector('textarea');
const button = document.querySelector('button');

button.addEventListener('click', async () => {
  try {
    await navigator.clipboard.writeText(textarea.value);
  } catch (err) {
    console.error(err.name, err.message);
  }
});

Live Demo

See the Pen Copy text to clipboard by Ranjith (@Ranjithkumar10) on CodePen.

The post How to copy text to the clipboard using Javascript? appeared first on Coding is Love.

]]>
https://codingislove.com/copy-text-clipboard-javascript/feed/ 0 4268
How to animate list reordering with React easily https://codingislove.com/animate-list-reordering-react/ https://codingislove.com/animate-list-reordering-react/#respond Mon, 26 Jun 2023 18:09:37 +0000 https://codingislove.com/?p=4246 Reordering a list and animating them is a very good user experience. Users will understand that the items’ order has changed clearly if we animate…

The post How to animate list reordering with React easily appeared first on Coding is Love.

]]>
Reordering a list and animating them is a very good user experience. Users will understand that the items’ order has changed clearly if we animate them. Without animation, the user experience would be bad and the user has to figure out what happened suddenly

Let’s see how to animate the list re-ordering easily using React and a library

List re-ordering using auto-animate

AutoAnimate is a zero-config, drop-in animation utility that adds smooth transitions to your web app. You can use it with React, Solid, Vue, Svelte, or any other JavaScript application.

In this blog post, we’ll look at how to use it in ReactJs

Installation

Install using your package manager of choice to add @formkit/auto-animate to your project:

Yarn

yarn add @formkit/auto-animate

NPM

npm install @formkit/auto-animate

Usage

Using auto-animate to re-order a list is very easy. All you need to do is use the useAutoAnimate hook and pass the return value to any list container. Once this is done, any element change i.e adding an element or removing an element or reordering an element will be auto-animated!

Here’s some example code:

import { useAutoAnimate } from '@formkit/auto-animate/react'

function MyList () {
  const [animationParent] = useAutoAnimate()
  return (
    <ul ref={animationParent}>
      {/* 🪄 Magic animations for your list */}
    </ul>
  )
}

Working demo

I’ve created a working demo in code sandbox to show how it works live. Here’s the code and the demo embedded below.

import { useAutoAnimate } from "@formkit/auto-animate/react";
import { useState } from "react";

import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <MyList />
    </div>
  );
}

function MyList() {
  const [animationParent] = useAutoAnimate();
  const [fruits, setFruits] = useState([
    { name: "Apple", emoji: "🍎" },
    { name: "Mango", emoji: "🥭" },
    { name: "Strawberry", emoji: "🍓" },
    { name: "Orange", emoji: "🍊" },
    { name: "Peach", emoji: "🍑" }
  ]);

  const moveUp = (fruit) => {
    // move the fruit up
    const fruitIndex = fruits.findIndex((f) => f.name === fruit.name);
    if (fruitIndex === 0) return;
    const newFruits = [...fruits];
    newFruits[fruitIndex] = fruits[fruitIndex - 1];
    newFruits[fruitIndex - 1] = fruit;
    setFruits(newFruits);
  };

  const moveDown = (fruit) => {
    // move the fruit down
    const fruitIndex = fruits.findIndex((f) => f.name === fruit.name);
    if (fruitIndex === fruits.length - 1) return;
    const newFruits = [...fruits];
    newFruits[fruitIndex] = fruits[fruitIndex + 1];
    newFruits[fruitIndex + 1] = fruit;
    setFruits(newFruits);
  };

  return (
    <article className="panel is-primary">
      <p className="panel-heading">Animate list re-ordering</p>
      <div className="panel-block has-text-weight-semibold">
        Tap on the arrows to reorder
      </div>
      <ul ref={animationParent}>
        {fruits.map((fruit, i) => (
          <li
            key={fruit.name}
            className="panel-block is-active is-flex is-justify-content-space-between"
          >
            <div>
              <span role="img" aria-label="apple" className="mr-2">
                {fruit.emoji}
              </span>{" "}
              {fruit.name}
            </div>
            <div className="is-flex">
              <div
                onClick={() => moveUp(fruit)}
                className={`mr-4 ${
                  i === 0 ? "has-text-grey-light" : "is-clickable"
                }`}
              >
                ▲
              </div>
              <div
                onClick={() => moveDown(fruit)}
                className={`${
                  i === fruits.length - 1
                    ? "has-text-grey-light"
                    : "is-clickable"
                }`}
              >
                ▼
              </div>
            </div>
          </li>
        ))}
      </ul>
    </article>
  );
}

Conclusion

Auto-animate can be used in many other use cases such as accordion, collapsible, animating form error messages, etc. I’ll write about it in a separate blog post but have fun reordering the list easily now!

Also, read How to create a collapsible in React easily

The post How to animate list reordering with React easily appeared first on Coding is Love.

]]>
https://codingislove.com/animate-list-reordering-react/feed/ 0 4246
How to create a card flip effect in React? https://codingislove.com/card-flip-effect-react/ https://codingislove.com/card-flip-effect-react/#respond Thu, 22 Jun 2023 16:51:55 +0000 https://codingislove.com/?p=4216 Do you want to create a flip card effect in ReactJS? Here’s how to do it easily using this library react-card-flip React-card-flip is an easy-to-use…

The post How to create a card flip effect in React? appeared first on Coding is Love.

]]>
Do you want to create a flip card effect in ReactJS? Here’s how to do it easily using this library

Card flip effect in ReactJS

react-card-flip

React-card-flip is an easy-to-use library to create a card flip effect. Let’s try it out!

Installation

To use react-card-flip, install it from NPM with npm using the command:

npm install --save react-card-flip

If you are using Yarn then install it from npm using the command:

install it from NPM with yarn using the command:

Usage

Import the ReactCardFlip component first

import ReactCardFlip from 'react-card-flip';

Provide the component with 2 children. The first child would be the front part and the second child would be the back part.

Create a property to hold the flip state of the card.

const [isFlipped, setIsFlipped] = useState(false);

Pass a property named ‘isFlipped’ to the ReactCardFlip component and a function to toggle the isFlipped state value. It would look something like this:

<ReactCardFlip isFlipped={isFlipped} flipDirection="vertical">
        <Card>
          <div style={{marginBottom: 15}}>This is the front of the card.</div>
          <button onClick={flipCard}>Click to flip</button>
        </Card>
        <Card>
        <div style={{marginBottom: 15}}>
          This is the back of the card.
          </div>
          <button onClick={flipCard}>Click to flip</button>
        </Card>
 </ReactCardFlip>

That’s it, You have a fully working flip effect! Here’s how it looks:

Card flip effect in ReactJS

Free source code

Here’s the source code of the complete example for you to run it live and use it in your apps.

The full demo is embedded below and here’s the link to source code – https://codesandbox.io/s/snowy-https-7r54cp

Go flip it!

Also read, Creating Engaging 3D Tilt Effects with vanilla-tilt.js

The post How to create a card flip effect in React? appeared first on Coding is Love.

]]>
https://codingislove.com/card-flip-effect-react/feed/ 0 4216
How to show a confirmation dialog before closing a web page? https://codingislove.com/show-confirmation-dialog-before-closing-web-page-before-unload/ https://codingislove.com/show-confirmation-dialog-before-closing-web-page-before-unload/#comments Fri, 16 Jun 2023 18:29:08 +0000 https://codingislove.com/?p=4169 When designing a web application or website, it’s common to include functionality that prompts users with a confirmation dialog before they leave or close the…

The post How to show a confirmation dialog before closing a web page? appeared first on Coding is Love.

]]>
When designing a web application or website, it’s common to include functionality that prompts users with a confirmation dialog before they leave or close the page. This feature is useful to prevent users from accidentally navigating away and losing unsaved changes.

In this blog post, we’ll explore how to implement a confirmation dialog using JavaScript’s beforeunload event.

The beforeunload Event

The beforeunload event is triggered when a user attempts to leave a page. By adding an event listener to this event, we can execute a function that displays a confirmation dialog before allowing the user to proceed.

Usage

We can use the beforeunload Event in 2 ways to show a confirmation dialog to user before leaving the page.

addEventListener method

window.addEventListener('beforeunload', function (event) {
  event.preventDefault();
  return (event.returnValue = "");
});

onbeforeunload property in HTML

<body onbeforeunload="return myFunction()">
<h1>The beforeunload Event</h1>

<p>Reload this page, or click on the link below to invoke the onbeforeunload event.</p>

<a href="https://codingislove.com">Click here to go to codingislove.com</a>
    
<script>
function myFunction() {
  event.preventDefault();
  return "";
}
</script>
</body>

Demo

Here’s a live demo below

Practical use case

Let’s say the user is filling out a form and he tries to exit the page, then we can show him a confirmation dialog that he has unsaved changes and get confirmation to proceed.

Try to use this event only for reasonable use cases to avoid any performance issues.

Unable to customize the message shown in onbeforeload?

If you are not able to change the confirmation message of onbeforeload event, that is because Starting in Chrome 51, a custom string will no longer be shown to the user. Chrome will still show a dialog to prevent users from losing data, but it’s contents will be set by the browser instead of the web page.

Chrome stopped support custom message in onbeforeload event from Chrome 51 because the developers were misusing this feature to scam the users! 😂

Browser Limitations

t’s important to note that different browsers may impose limitations on the customization of the confirmation dialog to prevent abuse or security issues. As a result, the appearance and behavior of the dialog may vary across platforms and browser versions.

Conclusion

We hope this blog post has provided you with a clear understanding of how to add a confirmation dialog before closing a web page. Happy coding ✌

The post How to show a confirmation dialog before closing a web page? appeared first on Coding is Love.

]]>
https://codingislove.com/show-confirmation-dialog-before-closing-web-page-before-unload/feed/ 1 4169