Days
Hours
Minutes
Seconds
x

New Froala Editor v4.5.2 is here – Learn More

Skip to content

Building a Responsive Website with a Bootstrap Editor: A Step-by-Step Guide

The digital world demands responsive web design as an essential requirement. Users access websites from phones, tablets, or desktop computers. Your website must deliver a smooth experience no matter the screen size. 

The solution is Bootstrap. The front-end framework Bootstrap provides developers with a comprehensive set of tools that accelerate and simplify responsive website development. The developer-friendly nature of Bootstrap may not appeal to users who prefer to avoid manual coding. Bootstrap editors serve as the perfect solution for users who need to create responsive websites.

The drag-and-drop interfaces and coding flexibility of Bootstrap editors allow users to build stunning responsive layouts without starting from scratch.

This guide provides a comprehensive pathway to build responsive websites with Bootstrap editors, covering everything from selecting the right tool to layout design and interactive additions, and concluding with live deployment.

What is Bootstrap, and why use it?

Bootstrap is a popular front-end framework originally developed by Twitter in 2011. It was built to help developers create consistent, responsive designs more efficiently. Today, it powers millions of websites and is currently in its fifth major version (Bootstrap 5), offering modern features and a mobile-first approach.

Key features

  • Grid System: Bootstrap’s 12-column layout makes it easy to create responsive page structures.
  • Components: Prebuilt elements like buttons, navbars, cards, and modals speed up development.
  • Utility Classes: Apply spacing, colors, alignment, and more directly in HTML.
  • Mobile-First Design: All components are designed to look great on small screens first.

Why choose Bootstrap?

Bootstrap stands out for its ease of use and flexibility. You can build sleek, functional websites without starting from scratch or writing a lot of custom CSS.

Pros:

  • Fast prototyping with reusable components.
  • Built-in responsiveness.
  • Strong community and documentation.
  • Easy to integrate with most editors and tools.

Cons:

  • May include more code than needed for small projects.
  • Customizing deeply can be challenging.
  • Websites can look similar if not styled further.

Overall, Bootstrap is a solid choice for building responsive sites quickly, especially when paired with a visual editor to simplify the process.

Check out all the Bootstrap classes here.

Overview of Bootstrap editors

When building responsive websites with Bootstrap, many developers also want to offer live editing capabilities — whether it’s for a content management system, admin panel, or inline content editing experience. That’s where WYSIWYG Bootstrap editors come into play.

These are not standalone site builders — instead, they are embeddable editors that integrate into your Bootstrap-based website, allowing users to edit content directly on the page while preserving Bootstrap’s layout and styling.

What is a Bootstrap-compatible WYSIWYG editor?

A Bootstrap-compatible WYSIWYG (What You See Is What You Get) editor is an embeddable content editor that works seamlessly with Bootstrap’s grid system, components, and utility classes. These editors let users update text, images, media, and layout blocks inside a live Bootstrap site without breaking responsive design.

WYSIWYG vs. Code-based editors

  • WYSIWYG editors like Froala are designed for non-technical users or content editors who need to make real-time updates without writing code. They’re often integrated into CMSs, admin dashboards, and SaaS applications.
  • Code-based editors, in contrast, are used by developers to manually write and maintain HTML/CSS/JS. They’re ideal for full-code control but aren’t suitable for non-technical content editing.

Bootstrap-compatible editors to consider

Here are some WYSIWYG editors that integrate well into Bootstrap-based websites:

  • Froala – A clean, lightweight, and highly customizable WYSIWYG HTML editor. Froala is Bootstrap-aware, supports inline editing, offers a responsive UI, and can be embedded directly into any Bootstrap project. It also supports custom toolbars, image uploads, code view, and works well in modern JavaScript frameworks.
  • TinyMCE – Another popular embeddable WYSIWYG editor that can be styled to match Bootstrap. Offers plugin-based customization and responsive layouts.
  • CKEditor – A rich editor that integrates with responsive frameworks, including Bootstrap. It has collaboration features and enterprise-ready tooling.

Note: Tools like Bootstrap Studio or Pinegrow are layout builders, not embeddable editors for Bootstrap websites. They are great for prototyping, but they don’t offer live, in-browser editing like Froala does.

How to choose the right WYSIWYG editor

When picking an editor for your Bootstrap website, consider:

  • Bootstrap Compatibility – Does the editor respect your existing layout and CSS classes?
  • Ease of Integration – Can it be easily embedded with minimal setup?
  • Responsiveness – Does it adapt across devices like your Bootstrap site?
  • Customizability – Can you extend or modify its UI and features?

If you’re looking to add live, responsive content editing to your Bootstrap website, Froala offers one of the smoothest and most developer-friendly integrations available.

Preparation: setting up your project

Before we dive into building our website, we need to set up a clean development environment. In this tutorial, we’ll create a dog adoption agency website to demonstrate how you can embed a WYSIWYG editor like Froala, use Bootstrap for layout and responsiveness, and integrate Filestack for handling images.

These tools work seamlessly together:

  • Bootstrap handles layout and design.
  • Froala provides inline content editing.
  • Filestack simplifies uploading and managing media.

Choosing a bootstrap-compatible editor

For this guide, we’re using Froala Editor. It’s a lightweight, embeddable WYSIWYG editor that fits perfectly into modern responsive websites. Froala is Bootstrap-aware — it respects your layout, classes, and components — and it allows users to edit content directly inside styled elements like cards, columns, or even modals.

Creating a new project

Start by organizing your files with a simple directory structure:

/bootstrap-froala-site

  ├── index.html

  ├── /css

  │   └── style.css

  ├── /js

  │   └── script.js

  └── /assets

      └── images/

This setup makes it easier to manage your code, styles, scripts, and media as your site grows.

Overview of bootstrap file structure

When building with Bootstrap 5, the core files you’ll need are:

  • bootstrap.min.css – for responsive styling and layout utilities.
  • bootstrap.bundle.min.js – includes Bootstrap’s interactive JavaScript components (like modals and dropdowns) and dependencies like Popper.js.

In addition, we’ll include:

  • Froala CSS/JS – to enable rich-text editing.
  • Filestack SDK – to enable media upload and processing.

Importing Bootstrap, Filestack, and Froala

Below is the basic HTML skeleton you can use. Notice that we’ve included Bootstrap, Filestack, and Froala scripts. These files enable you to leverage Bootstrap for responsive layout, work with Filestack for image handling, and embed Froala for live content editing:

index.html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Dog Adoption Agency</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap CSS -->

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">

    <!-- Froala Editor CSS -->

    <link href='https://cdn.jsdelivr.net/npm/[email protected]/css/froala_editor.pkgd.min.css' rel='stylesheet'

        type='text/css' /> <!-- Filestack JS and CSS (Picker, Drag-and-Drop, Transforms) -->

    <script src="https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js"> </script>

    <script

        src="https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js"> </script>

    <script src="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js"> </script>

    <link rel="stylesheet" href="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css" />

    <!-- Froala Editor JS -->

    <script type='text/javascript'

        src='https://cdn.jsdelivr.net/npm/[email protected]/js/froala_editor.pkgd.min.js'> </script>

</head>

<body> <!-- Content goes here --> <!-- Bootstrap JS -->

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"> </script>

</body>




</html>

With this setup, you’re ready to start building your dog adoption agency website with embedded editing, responsive layout, and modern media capabilities.

Step-by-step: Building your responsive website

With our project environment set up and Bootstrap, Froala, and Filestack integrated, let’s start building the dog adoption agency website section by section. We’ll walk through how to structure the layout, embed interactive components, and bring the site to life using Bootstrap’s utility classes and JavaScript components — all while enabling rich content editing and image uploads.

Step 1: Build a sticky navbar

Start with a Bootstrap sticky navbar that stays fixed to the top as users scroll. It contains anchor links that smoothly guide users to each section of the page.

index.html – inside the <body> tag

<nav class="navbar navbar-expand-lg navbar-dark bg-dark sticky-top">

  <div class="container-fluid">

    <a class="navbar-brand" href="#">DogAdopt</a>

    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">

      <span class="navbar-toggler-icon"></span>

    </button>

    <div class="collapse navbar-collapse" id="navbarNav">

      <ul class="navbar-nav ms-auto">

        <li class="nav-item"><a class="nav-link active" href="#">Home</a></li>

        <li class="nav-item"><a class="nav-link" href="#adopt">Adoptable Dogs</a></li>

        <li class="nav-item"><a class="nav-link" href="#pricing">Pricing</a></li>

        <li class="nav-item"><a class="nav-link" href="#comment">Comment</a></li>

      </ul>

    </div>

  </div>

</nav>

Step 2: Create a hero section

Use a simple Bootstrap hero layout to grab attention with a clear message and call to action.

index.html – inside the <body> tag

<section class="bg-light text-dark py-5 text-center">

  <div class="container">

    <h1 class="display-4">Save a Life, Adopt a Dog</h1>

    <p class="lead">Join our community and give a loving home to these adorable companions.</p>

    <a href="#adopt" class="btn btn-primary btn-lg">Find Your Companion</a>

  </div>

</section>

So far, your page should look something like this:

Froala Bootstrap website - after adding hero section

Step 3: Add an image carousel

Bootstrap’s carousel component highlights adoptable dogs using high-quality Filestack-transformed images.

index.html – inside the <body> tag

<!-- Add an image carousel -->
    <div id="dogCarousel" class="carousel carousel-dark slide" data-bs-ride="carousel">
        <div class="carousel-indicators"> <button type="button" data-bs-target="#dogCarousel" data-bs-slide-to="0"
                class="active" aria-current="true"></button> <button type="button" data-bs-target="#dogCarousel"
                data-bs-slide-to="1"></button> <button type="button" data-bs-target="#dogCarousel"
                data-bs-slide-to="2"></button> </div>
        <div class="carousel-inner">
            <div class="carousel-item active"> <img
                    src="https://cdn.filestackcontent.com/resize=width:1200,height:500/hmzhYgUSZiIA0Ju2ocMo"
                    class="d-block w-20" alt="Friendly Dog 1"> </div>
            <div class="carousel-item"> <img
                    src="https://cdn.filestackcontent.com/resize=width:1200,height:500/xsFLOcdRYKQOz4oQpmgg"
                    class="d-block w-20" alt="Friendly Dog 2"> </div>
            <div class="carousel-item"> <img
                    src="https://cdn.filestackcontent.com/resize=width:1200,height:500/e0DUJOjTjWmUQm0FxL7e"
                    class="d-block w-20" alt="Friendly Dog 3"> </div>
        </div> <button class="carousel-control-prev" type="button" data-bs-target="#dogCarousel" data-bs-slide="prev">
            <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span
                class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button"
            data-bs-target="#dogCarousel" data-bs-slide="next"> <span class="carousel-control-next-icon"
                aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button>
    </div>

Update the image URLs with your Filestack handles or transformed links.

To center the images within the carousel, add the following CSS. You can place it in your style.css file (if you’re using a separate stylesheet) or directly in your index.html file, just inside the <style> tag and placed within the <head> section.

Style.css

 

<style>

    .carousel-inner img {

        margin: auto;

    }

</style>

Here’s how your page should be shaping up so far:

Froala Bootstrap page after adding carousel

Step 4: Enable image upload with Filestack

Embed a Filestack picker to let users upload new dog images:

index.html – inside the <body> tag

<!-- Filestack Mini-Section -->

    <section class="py-4 text-center">

        <div class="container">

            <h3>Upload a picture of your own dog</h3>

            <p>Upload and transform images directly, then embed them on your site.</p>

            <button class="btn btn-secondary" onclick="openFilestackPicker()">Upload a New Dog Image</button>

        </div>

    </section>

<script>

    const client = filestack.init('YOUR_API_KEY'); // Replace 'YOUR_API_KEY' with your actual Filestack API key. 

    function openFilestackPicker() {

        client.picker({

        onUploadDone: (res) => {

            console.log('Uploaded file handle:', res.filesUploaded[0].handle);

        }

        }).open();

    }

 </script>

Replace ‘YOUR_API_KEY’ with your actual Filestack API key.

Sign up for free today to get your Filestack API key.

You can also place the script in a separate script.js file and reference it in the <body> section of your index.html file like this:

<script src="js/script.js"></script>

Make sure the path matches your folder structure (e.g., js/ in this case).

Froala Bootstrap webpage after adding Filestack file uploader

Step 5: Display adoptable dogs with cards

Showcase adoptable dogs using Bootstrap cards:

index.html – inside the <body> tag

<!--Display adoptable dogs with cards-->    

<section id="adopt" class="py-5">

        <div class="container">

            <h2 class="mb-4 text-center">Meet Our Adorable Dogs</h2>

            <div class="row">

                <div class="col-md-6 col-lg-4 mb-4">

                    <div class="card"> <img

                            src="https://cdn.filestackcontent.com/resize=width:1200,height:500/hmzhYgUSZiIA0Ju2ocMo"

                            class="card-img-top" alt="Buddy">

                        <div class="card-body">

                            <h5 class="card-title">Buddy</h5>

                            <p class="card-text">A playful pup who loves belly rubs and afternoon walks.</p> <a href="#"

                                class="btn btn-primary">Adopt Buddy</a>

                        </div>

                    </div>

                </div>

                <div class="col-md-6 col-lg-4 mb-4">

                    <div class="card"> <img

                            src="https://cdn.filestackcontent.com/resize=width:1200,height:500/xsFLOcdRYKQOz4oQpmgg"

                            class="card-img-top" alt="Lucy">

                        <div class="card-body">

                            <h5 class="card-title">Lucy</h5>

                            <p class="card-text">A gentle soul who gets along with children and other pets.</p> <a href="#"

                                class="btn btn-primary">Adopt Lucy</a>

                        </div>

                    </div>

                </div>

                <div class="col-md-6 col-lg-4 mb-4">

                    <div class="card"> <img

                            src="https://cdn.filestackcontent.com/resize=width:1200,height:500/e0DUJOjTjWmUQm0FxL7e"

                            class="card-img-top" alt="Max">

                        <div class="card-body">

                            <h5 class="card-title">Max</h5>

                            <p class="card-text">A loyal companion who enjoys fetch and lazy afternoons.</p> <a href="#"

                                class="btn btn-primary">Adopt Max</a>

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </section>

Froala Bootstrap webpage displaying adoptable dogs with cards

Step 6: Add a pricing section with cards

Showcase your adoption packages using Bootstrap cards combined with utility classes for spacing and layout.

index.html – inside the <body> tag

<!--Add Pricing section-->

    <section id="pricing" class="bg-light py-5">

        <div class="container text-center">

            <h2 class="mb-4">Adoption Packages</h2>

            <div class="row">

                <div class="col-md-4 mb-4">

                    <div class="card h-100">

                        <div class="card-body">

                            <h5 class="card-title">Basic</h5>

                            <p class="card-text">$50 Donation</p>

                            <ul class="list-unstyled">

                                <li>Initial Checkup</li>

                                <li>Vaccinations</li>

                            </ul> <a href="#" class="btn btn-primary">Adopt Now</a>

                        </div>

                    </div>

                </div>

                <div class="col-md-4 mb-4">

                    <div class="card h-100">

                        <div class="card-body">

                            <h5 class="card-title">Standard</h5>

                            <p class="card-text">$100 Donation</p>

                            <ul class="list-unstyled">

                                <li>All Basic Perks</li>

                                <li>Pet Insurance (6 months)</li>

                            </ul> <a href="#" class="btn btn-success">Adopt Now</a>

                        </div>

                    </div>

                </div>

                <div class="col-md-4 mb-4">

                    <div class="card h-100">

                        <div class="card-body">

                            <h5 class="card-title">Premium</h5>

                            <p class="card-text">$150 Donation</p>

                            <ul class="list-unstyled">

                                <li>All Standard Perks</li>

                                <li>Lifetime Vet Support</li>

                            </ul> <a href="#" class="btn btn-warning">Adopt Now</a>

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </section>

Froala Bootstrap webpage after adding Pricing

Step 7: Add a comment section with Froala

Enable live WYSIWYG editing using Froala Editor for user comments.

<!--Adding a Bootstrap Editor WYSIWYG Froala-->
    <section id="comment" class="py-5">
        <div class="container">
            <h2 class="mb-4 text-center">Leave a Comment</h2>
            <div id="editor"></div>
        </div>
    </section>
    <script> var editor = new FroalaEditor('#editor', {
        imageEditButtons: ['imageReplace', 'imageAlign', 'imageCaption', 'filestackIcon', 'imageTUI'], filestackOptions: {
            uploadToFilestackOnly: false, filestackAPI: '***', // Replace with your Filestack API key 

            pickerOptions: { fromSources: ['local_file_system', 'imagesearch', 'url', 'googledrive', 'facebook'], accept: [".pdf", "image/jpeg", "image/png", "image/webp", "video/*", "audio/*"], transformations: { crop: true, rotate: true } }
        },
    }); 
    </script>

Add a comment section with Froala

With these steps, your responsive website now includes:

  • A mobile-friendly layout with Bootstrap
  • Live content editing powered by Froala
  • Image uploads and transformations via Filestack

Check out the full example on our GitHub repo!

Next, we’ll look at testing, optimization, and going live.

Testing and optimization

Before going live, ensure your site looks great and performs well across all devices.

Preview and test

  • Use Chrome DevTools or built-in browser tools to preview different screen sizes.
  • Test on major browsers like Chrome, Firefox, Safari, and Edge.
  • View your site on real phones or tablets when possible.
Responsive preview of the dog adoption website built with Bootstrap, Froala and Filestack (iPad view)
Responsive preview of the dog adoption website built with Bootstrap, Froala and Filestack (iPad view)

Optimize performance

  • Minify your HTML, CSS, and JS files to reduce load time.
  • Compress and resize images using Filestack or similar tools.
  • Use lazy loading for images and videos to boost speed, especially on mobile.

Exporting and going live

Once your dog adoption website is complete, it’s time to bring it online. This final step outlines how to export your project, host it, and make it accessible to users worldwide.

Exporting your project

If you’ve been working in an online editor, download your full project as a .zip file or copy the HTML, CSS, and JS files manually. If you’re developing locally, your index.html, css/, and js/ folders are already ready to deploy.

Hosting options

You can host your site for free using services like:

  • GitHub Pages – Ideal for static HTML/CSS projects and version control.
  • Netlify – Offers drag-and-drop deployment, custom domains, and CI/CD support.
  • Vercel – Great for frontend developers; supports instant previews and easy deployment.

Connecting a domain

After hosting your site, you can connect a custom domain:

  • Purchase a domain from registrars like Namecheap or GoDaddy.
  • Point the domain’s DNS to your hosting provider (e.g., add A records for Netlify or GitHub).
  • Most platforms provide step-by-step domain setup guides.

This example guide is provided by Namecheap.

Basic SEO and meta tags

To improve visibility and search performance:

  • Add a <title> tag and a descriptive <meta name=”description”> to your HTML <head>.
  • Use semantic HTML (e.g., <header>, <main>, <section>).
  • Include alt text for images and ensure the site is mobile-friendly.

Example:

 

<!-- Example meta tags -->

<title>DogAdopt – Adopt a Dog Today</title>

<meta name="description" content="Find and adopt your perfect dog companion. Browse dogs, learn about adoption, and support a great cause.">

With these steps, your Bootstrap + Froala-powered website is live and ready to help dogs find their forever homes.

Advanced tips and next steps

Once your Bootstrap website with Froala and Filestack is up and running, you may want to take it a step further. Here are a few ways to level up your skills and make your site even more powerful, customized, and accessible.

Integrate with modern frameworks

If you’re building a more dynamic or scalable project, consider integrating Bootstrap with popular JavaScript frameworks like:

  • React (with react-bootstrap or reactstrap)
  • Angular (using ng-bootstrap)
  • Vue (with bootstrap-vue)

These integrations allow you to combine Bootstrap’s styling with framework-specific component logic and interactivity.

Use Bootstrap themes and templates

Speed up design by using pre-built Bootstrap themes or UI kits. You can:

Learn SCSS for deeper customization

Bootstrap is built with Sass, and learning it unlocks powerful features:

  • Change default colors, spacing, and breakpoints.
  • Import only the components you need to reduce file size.
  • Build fully custom design systems on top of Bootstrap.

Prioritize accessibility

Make your site usable for everyone by applying accessibility best practices:

  • Use semantic HTML and ARIA roles.
  • Maintain color contrast for readability.
  • Ensure full keyboard navigation for all interactive elements.

You can test accessibility with tools like Lighthouse, Axe DevTools, or WAVE.

Conclusion

In this tutorial, we walked through how to build a fully responsive dog adoption website using Bootstrap, Froala, and Filestack. You learned how to:

  • Set up your project structure and import essential tools
  • Create a clean, mobile-friendly layout with Bootstrap
  • Enable inline content editing with Froala
  • Upload and manage media using Filestack
  • Test, optimize, and publish your site with ease

This guide highlights the power and efficiency of modern web development when combining Bootstrap with embeddable editors like Froala and tools like Filestack.

Now it’s your turn to experiment! Try adding new sections, customizing styles, or integrating this layout into a CMS or app. The best way to learn is by building, breaking, and rebuilding.

If you have questions, want to share your own version, or need help with the next step—feel free to drop a comment or open an issue in the GitHub repo.

Happy coding, and happy adopting!

 

Easily Add Powerful Table Sorting with DataTables Plugin

Froala Table Sorting

Introduction to the Froala Editor Integration

Do you find the Froala editor the perfect rich text editor for your project, but require robust table sorting capabilities? No problem! The Froala editor is a highly extensible WYSIWYG HTML editor, making it remarkably easy for developers to add the specific table sorting functionality you need using a suitable plugin.

Many developers rely on the Froala editor for its powerful features and ease of use when constructing HTML pages. This editor simplifies the content creation experience.

This article demonstrate how straightforward it is to integrate a table sorting feature into the Froala editor. We’ll achieve this by leveraging the popular DataTables JavaScript library, acting as a powerful plugin. This example showcases how the flexibility of the Froala editor allows developers to enhance this excellent editor with the exact tools their project requires – even if a specific capability isn’t in the core editor.

This example should provide a clear path for many developers looking to add advanced table controls. We will provide essential code examples below, showing how developers can implement this feature. The editor becomes much more powerful with this plugin.

You’ll see how the Froala editor empowers users and developers to create sophisticated editable content. This specific example focuses on table manipulation within the editor, using external library code. The goal is to improve how users interact with table data within the editor.

Froala Table Sorting

Key Takeaways

  • Implementing Froala table sorting significantly improves data usability and the overall user experience for manipulating table data within the Froala editor.
  • Integrating the DataTables plugin enhances the core functionality of Froala editor tables, adding sorting to each column. This plugin is a great example for developers. Using this plugin requires including specific code.
  • Performance optimization is essential when the editor needs to handle tables with numerous rows and large data sets; developers must consider this when adding custom code.

The Power of Froala Tables in a WYSIWYG Editor

The Froala WYSIWYG editor already includes robust table editing functionality out of the box. People using the editor can easily create, modify, and format tables directly within the rich text editor.

Native capabilities like multi-cell selection, cell merging, and custom style options (even controlling border collapse or font family) make Froala tables a cut above many other editor solutions.

But the native table features in the Froala editor can be further enhanced by integrating with the powerful DataTables library integration. DataTables provides advanced sorting, filtering, paging (rows per page), and other table management capabilities that complement Froala’s built-in table edit tools within the editor.

This plugin adds significant ability through its JavaScript code. This plugin is a popular choice for developers working with tables in web applications and the Froala editor. The editor becomes a more complete tool for data presentation.

Importance of Table Sorting within the Rich Text Editor

Okay, so you’ve used the editor to create a table. Great! But what if users need to find specific data within its rows? That’s where sorting comes in. Table sorting is important because it lets users quickly organize data in a way that makes sense within the editor.

Imagine a table with a list of customers. Without sorting, users would have to manually scan all the rows to find someone. But with sorting enabled by the plugin, users can instantly arrange the table by name, order date, or whatever column they need. This saves a ton of time and makes your table data way more useful for anyone using the editor.

It’s not just about finding stuff faster, though. Sorting tables can also help users highlight trends and patterns in their data that they might otherwise miss inside the editor. For example, sorting a sales table by revenue could quickly highlight your top-performing products. The editor makes managing this table data easier for users.

Here are some reasons why sorting within the editor is important for developers and end-users:

  • Faster data retrieval from tables for users.
  • Improved data analysis within the editor by users.
  • Enhanced user experience for those interacting with the editable content in the Froala editor. This example clearly shows the benefit of adding this plugin code. The editor feels more interactive.

Froala Table Sorting – How it works

There are several ways developers can add table sorting support to the Froala editor using any JavaScript HTML table enhancing library or plugin. In this guide and code example, we’ll use the popular DataTables library.

DataTables provides advanced sorting, filtering, and pagination features that complement the Froala editor’s built-in table edit tools. We select this plugin due to its extensive features, good documentation for developers, and ease of integration with the editor via simple code additions.

This JavaScript library is a common choice for enhancing HTML tables. Its code is widely used by developers. It interacts directly with the table elements within the editor.

The approach or method we’ll take has the following key steps:

  1. Add a new custom button to the Froala editor table edit popup (menu) that initializes the DataTables plugin on the selected table. The necessary code is shown below.
  2. This will enhance the table, adding sorting buttons (visual signs) to each column header cell.
  3. Users can then click these buttons to sort the table data in ascending or descending order. The underlying code handles the table row manipulation directly in the editor.
  4. This tutorial serves as a good starting point example for integrating the Froala editor with the DataTables library plugin. However, developers may need to optimize the provided code further to handle certain scenarios, such as when a user adds new rows and columns to the table after initializing the DataTables on it. In this case, developers may need to re-initialization the DataTables on the modified table.

Adding the Froala Table Sorting Feature: A Code Example

Adding this table sorting capability via the DataTables plugin to your Froala editor setup is a straightforward process. Here are the key steps involved in this setup:

Step 1: Include the Required Libraries (CSS & JS Code)

To get started with this editor enhancement, developers must include the following CDN links in their web page:

  • Froala WYSIWYG Editor Stylesheet and JavaScript CDN links
  • DataTables JavaScript library (which requires jQuery)
  • Font Awesome stylesheet for custom button icons
 
<!-- Font Awesome library for icons -->
<link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.5.0/css/all.min.css' rel='stylesheet' type='text/css' />

<!-- Froala editor stylesheet -->
<link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />

<!-- DataTables stylesheet -->
<link href='https://cdn.datatables.net/2.2.2/css/dataTables.dataTables.min.css' rel='stylesheet' type='text/css' />

<!-- jQuery script -->
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js'></script>
<!-- DataTables script -->
<script type='text/javascript' src='https://cdn.datatables.net/2.2.2/js/dataTables.min.js'></script>
<!-- Froala script -->
<script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>

Step 2: Create a New Custom Button For Froala

Let’s create a custom button within the Froala editor system to enable the sorting function on the selected table.

We will use the “filter” Font Awesome icon (font) to represent our button in the editor toolbar. Add this JavaScript code before initializing the Froala editor.

// Use Font Awesome icons
FroalaEditor.ICON_DEFAULT_TEMPLATE = "font_awesome_5" 

//Define icon for "advancedTable" buttton
FroalaEditor.DefineIcon("advancedTable", { NAME: "filter" })

This code tells the editor how to display the button icon using the specified font.

2.2 Define the Button Function (Command Code)

Now, let’s register one of the Froala editor commands that executes our table sorting logic using the DataTables plugin. This code defines the button’s action. Place this code before the editor initialization.

The following code block shows the command registration.

FroalaEditor.RegisterCommand("advancedTable", {   
   title: "Advanced Table",   undo: true,
   callback: function callback(cmd) {
     let table = this.$el.find(".fr-selected-cell").closest("table");
     if (table[0] && table[0].getElementsByTagName("thead").length > 0) {
       let advTable = new DataTable(table, {
         searching: false,
         paging: false,
       });
     } else {
       alert("You should add a table header first.");
     }
   },
 });

In the above JavaScript code:

  • We registered a new Froala editor button command with the name “advancedTable”.
  • The button will be represented by the font icon we defined in the previous step using separate code. It will appear on the table edit menu.
  • It has a title attribute shown as a tooltip in the editor.
  • The callback function contains the core logic. This function code runs when the button is clicked by a user in the editor.
  • It finds the parent table HTML element from the currently selected table cell within the editor. This part of the code uses jQuery selectors provided by the Froala editor.
  • Crucially, it checks if the selected table has a header row (<thead> tag). This is a requirement for the DataTables plugin code to identify columns for sorting.
  • If a header row exists, it initializes the DataTables plugin (new DataTable(…)) on the HTML table DOM element. Note the options object uses false for searching and paging in this specific code example. This code line activates the plugin. The boolean value false turns those features off.
  • If no header row is found, it displays an alert message. This ensures the DataTables plugin functionality works as expected.
  • This code provides the essential mechanism for developers to trigger the plugin. It’s the core integration code.

Step 3: Initialize the Froala Editor

Finally, developers need to setup the Froala Editor instance on their page. This usually involves targeting a textarea HTML element or a div. Add the new “advancedTable” button to the tableEditButtons array in the editor configuration options.

This code integrates our custom button into the editor’s table edit menu. The following code block shows the editor initialization. This code makes the editor appear on the page.

new FroalaEditor("#editor", {
  tableEditButtons: [
    "tableHeader",
    "tableRemove",
    "|",
    "tableRows",
    "tableColumns",
    "tableStyle",
    "-",
    "tableCells",
    "tableCellBackground",
    "tableCellVerticalAlign",
    "tableCellHorizontalAlign",
    "tableCellStyle",
    "|",
    "advancedTable",
  ],
})

This final block of code:

  • Creates the Froala editor instance, targeting an HTML element (e.g., <textarea id="editor"></textarea> or <div id="editor"></div>). This HTML element becomes the editor element where users edit content.
  • Crucially, advancedTable is added to the tableEditButtons array. This makes our custom button appear in the table edit menu within the editor.
  • Developers can add many other options to this initialization code to customize the editor (e.g., license key, height, available font size, font family options like sans serif, event handlers, other plugins). This example code shows only the essential part for adding the button. The Froala documentation lists all available code options.
  • This editor setup code should run after the page’s HTML body is loaded and the previous JavaScript code (icon and command definition) has executed. Ensure all prerequisite code is loaded.

Testing the Froala Table Sorting Feature

Once the Froala editor is set up with the new “Advanced Table” button using the provided code, users and developers can test it:

  1. Insert a new table into the editor’s editable content area using the toolbar.
  2. Add content to the table rows and columns. Make sure to add a header row using the editor’s table menu. Each table cell should contain appropriate data. The table needs a <thead> for the plugin code to work.
  3. Click inside any table cell of the table you want to sort within the editor.
  4. The table edit toolbar / popup menu should appear. Find and click the “Advanced Table” button (the one with the filter font icon).
  5. The DataTables plugin code will execute, enhancing the table. Users should see sorting icons (a visual sign) appear in each column header cell. These icons are often added via CSS defined in the plugin’s stylesheet code.
  6. Click these column headers to sort the table data within that column in ascending or descending order. The rows will rearrange directly within the editor, handled by the plugin’s code.


This integration allows Froala editor users to leverage the advanced table management features of the DataTables plugin while still maintaining the rich edit capabilities of the Froala WYSIWYG HTML editor. This enhances the content creation experience. Try pasting data into the table as well. Users can edit table cell content freely after sorting. The editor remains fully functional.

Advanced Configurations for Froala Table Sorting

While the default DataTables plugin integration (using the minimal code shown) provides a great baseline table sorting functionality, developers may want to further customize the experience. DataTables offers a wide range of configuration options in its code API.

Developers can modify the initialization code (example: the options object { searching: false, paging: false } passed to new DataTable(…) in the command’s code) to:

  • Implement pagination by setting paging to true instead of false and control the number of rows displayed per page. The plugin code handles this display logic.
  • Customize the applied CSS classes for different table states. Apply custom border styles or width controls using your own CSS code. The plugin adds specific CSS classes that developers can target.
  • Define custom sorting functions (function code) for specific data types (e.g., dates, currency) if the default plugin sorting isn’t sufficient. This involves writing more JavaScript code for the plugin.
  • Change the sorting mode (e.g., multi-column sorting). Requires different options in the initialization code.
  • Control the position of elements like the search box or pagination controls relative to the table using CSS code.

Leveraging these configurability options in the code requires more effort from developers but allows tailoring the table sorting experience within the Froala editor to perfectly fit the needs of your project and the people using the editor. Consult the DataTables plugin documentation for full details and more code examples. Many developers find the plugin very flexible. You can find many code examples online for this plugin.

Handling Dynamic Table Changes (Developer Considerations for Table Columns and Cells)

One potential challenge for developers when integrating the Froala editor and the DataTables plugin using the provided code is handling scenarios where the user adds, removes, or modifies table rows, table columns, or table cell content after the DataTables plugin initialization code has run. The sorting state might become inconsistent with the actual table data in the editor.

To address this, developers must implement more sophisticated code:

  1. Store References: Keep track of the DataTables instances initialized on each table within the editor. Developers could use JavaScript code to manage this, perhaps using a Map keyed by table IDs.
  2. Listen to Froala Events: Use the Froala editor’s event system (like contentChanged, table.inserted, commands.after, etc.) by adding event handlers in the editor initialization code. These editor events signal changes to the HTML. Developers need to write listener code.
  3. Update or Re-initialize DataTables: When relevant editor events fire for a specific table, get the corresponding DataTables instance using your tracking code. Developers might need to write code to:
  • Destroy the existing DataTables instance (table.destroy()) and re-initialize the plugin on the modified HTML table structure using the original initialization code. This is often the simplest method for developers to ensure the plugin sees all HTML changes, including new rows or changes affecting border or width. This requires careful execution of code.

Developers must test these scenarios thoroughly in different browser environments. Look for code examples online or in documentation for handling these dynamic updates in the editor.

Frequently Asked Questions about the WYSIWYG HTML Editor and Plugin

What is Froala WYSIWYG HTML Editor?

Froala is a powerful, front-end WYSIWYG HTML editor (a type of rich text editor) that allows people (users) to easily create and edit HTML content directly in a web page, often replacing a standard textarea. It’s known for its clean interface and extensive API (code methods and events) for developers. It provides a great content creation experience. The editor renders HTML tags visually.

Why use DataTables with the Froala Rich Text Editor?

Using the DataTables plugin with the Froala editor adds powerful features for managing HTML tables, like sorting by column, filtering data, and pagination across multiple rows. This makes it much easier for people using the editor to work with large amounts of table data. It enhances the core editor functionality via external code. This plugin makes the editor more suitable for data-heavy content.

How do I integrate DataTables into my Froala editor setup?

Developers can integrate the DataTables plugin by including the necessary DataTables CSS and JavaScript library code (https links) in their project’s HTML page (often in the <head> or before the </body> tag).

Then, write JavaScript code (like the example in this article) to initialize the plugin on specific HTML table elements within the Froala editor’s editable content area, usually triggered by a custom button defined with editor API code.

Does Froala integrate with DataTables in Inline Editor mode?

Yes, the Froala-DataTables integration can also be used in Froala’s Inline Editor mode. The inline editor mode is used when the user wants to minimize the disruptions and maintaining the page layout during the editing process.

Does Froala support multiple table cell editing?

Yes, Froala does support multiple cell table editing. Users can select multiple cells and apply formatting, styles, or other operations across the selected range. This enables powerful table management capabilities within the Froala WYSIWYG editor. By leveraging DataTables sorting alongside Froala’s multi-cell editing, users can efficiently organize and structure tabular data to meet their specific requirements. The combination of these features provides a robust and flexible table editing experience within the Froala editor.

Does Froala support image uploads within tables?

Yes, Froala allows users to insert images directly within table cells, providing a seamless way to incorporate visual elements alongside tabular data. This flexibility enables content creators to build rich and visually engaging tables that blend text, numbers, and imagery. The integration of image uploads within Froala’s table editing capabilities empowers users to create more dynamic and informative tabular content, enhancing the overall presentation and effectiveness of the information being conveyed.

How to modify table cell font family and size?

To modify the font family and size of table cells in the Froala WYSIWYG editor, you can use the editor toolbar. Moreover, you can set a specific font family and size in a CSS class and apply that class to the desired cell using the “tableCellStyles” button.

Conclusion

Integrating the Froala editor with the DataTables JavaScript library plugin is an excellent method for developers to provide a comprehensive table management experience for users. Froala’s built-in table edit capabilities, combined with the advanced sorting provided by the DataTables plugin, create a powerful solution for content-rich web applications needing sophisticated table interactions within a rich text editor. The ability to sort rows by column is crucial for data analysis within the editor.

By following the simple steps and the code examples outlined in this article, and further customizing the integration code and CSS style to meet your specific needs, developers can quickly add this valuable feature to their projects using the Froala editor. This empowers people using the editor with a best-in-class table editing and data exploration experience, improving the overall content creation experience.

Elevate Your Delphi Web Application with Seamless Rich Text Editing: Mastering Froala TMS Web Core Integration

As a Delphi developer, you know the importance of building modern, responsive web applications with a great user experience. The TMS WEB Core framework is a powerful tool for creating such apps, but what if you need a robust WYSIWYG (What-You-See-Is-What-You-Get) editor for your content management features?

No worries, the TMS WEB Core framework has a WEB Component for integrating Froala, a powerful WYSIWYG Editor, allowing Delphi web applications to seamlessly incorporate rich text editing capabilities and enhance user experience.

In this step-by-step guide, we’ll walk you through the simple process of integrating the Froala editor into your TMS WEB Core Delphi applications. By leveraging the power of Froala and the flexibility of TMS WEB Core, you can deliver a high-quality content management solution within your Delphi web projects.

Why Use the TMS WEB Core Framework?

The TMS WEB Core framework is the foundation of an exciting new and modern way for creating web client applications from Delphi using a component-based framework. Some key benefits of using TMS WEB Core include:

  • Cross-platform compatibility: TMS WEB Core allows you to create web applications that can run on a variety of platforms, including Windows, macOS, and Linux.
  • Rapid development: The framework provides a wealth of pre-built components and tools, enabling you to quickly build and deploy feature-rich web applications.
  • Seamless integration: TMS WEB Core integrates seamlessly with other Delphi technologies, such as the Froala WYSIWYG Editor, allowing you to create a cohesive and efficient development ecosystem.
  • Modern web standards: The framework is built on the latest web technologies, ensuring your applications are up-to-date and provide an optimal user experience.
  • The TMS WEB Core web client application is open to work with different server technologies. This includes but is not limited to Embarcadero RAD Server, Node.js, ASP.NET Core microservices.

Why Integrate Froala Editor with TMS WEB Core?

The Froala WYSIWYG HTML Editor is a lightweight WYSIWYG HTML editor. However, it is a feature-rich, customizable editor that allows users to easily format text, insert images, and more, all without needing to write HTML code.

Some key benefits of this integration include:

  • Intuitive WYSIWYG editing experience for your users
  • Extensive customization options to match your app’s branding and design
  • Robust feature set including table manipulation, responsive video embedding, and more
  • Seamless integration with the TMS WEB Core framework for a cohesive user experience

Froala TMS Web Core Integration Guide

The TMS WEB Core offers the TMSwebFroalaEditor WEB Component that simplifies the Froala Editor integration with TMS WEB Core framework. The integration process is straightforward, allowing you to quickly set up the Froala editor, saving a lot of development time and effort.

Integrate the Froala WYSIWYG Editor into your TMS WEB Core Delphi application using the TMSwebFroalaEditor component by following these steps:

Step 1: Install the RAD Studio IDE

As a Delphi developer, you may already be using RAD Studio. If not, we recommend installing it. RAD Studio is an advanced IDE for rapidly and visually building high-performance platform-native apps for Windows, Linux, iOS, macOS and Android from a single codebase.

Step 2: Install the TMS WEB Core Framework

The TMS WEB Core is a framework for creating modern web applications in Delphi. You can download and install the latest version of the framework from the official TMS Software website. Download the version compatible with your RAD Studio. The integration requires TMS WEB Core version 1.2.3.0 or newer.

Step 3: Install the TMSwebFroalaEditor Component

    1. Download and install the TMSwebFroalaEditor component from the TMS Software website.Froala Editor TMS WEB Core component
  1. Extract the downloaded ZIP file: it contains the following folders:
    • The “Component Library Source” folder,
    • The “Core Source” folder.
    • The “Demo” folder.
  2. Add the Library path: Add the “Core Source” folder path to the TMS WEB library path (RAD Studio: Tools > Options > TMS WEB > Library Path). Restart RAD Studio afterwards to ensure changes are applied.
  3. Install the package file “TMSWEBFroalaEditor”:
    1. Open the "Component Library Source/TMSWEBFroalaEditor.dpk" package file in the Rad Studio.
    2. This package requires the TMSWEBCorePkgLibDXE11.dcp library. Update this line if you are using a different TMS WEB Core version.
    3. Compile the package: Right-clicking on the package in the Project Manager and selecting “Compile”.
    4. Install the package: Right-clicking on the package in the Project Manager and selecting “Install”. Now you are ready to use the component in your project.

Step 4: Play with the Demo

The demo illustrates displaying the Froala Editor within your TMS WEB Core Delphi application. To run it, you need to do the following steps:

    1. Open the Demo Project: Locate the "Demo/FroalaEditor.dpk" package file in the downloaded ZIP folder and open it in your RAD Studio IDE.
    2. Include Froala Editor: Open “Index.html“ file. Note, the code assumes you will download the Froala Editor files and host them on your server. However, you can replace the local Froala stylesheet and JavaScript links with CDN links so we don’t need to download it. 
      <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />
      
      <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>

       

    1. Understand the Demo Structure: The demo project likely consists of several files, including:
      • FroalaEditor.dpr: The main project file.
      • FroalaEditorForm.pas: The main form file, which contains the Froala Editor component and other UI elements.
    2. Run the Demo: To run the demo application, simply click the “Run” button in your RAD Studio IDE. This will compile and launch the demo, allowing you to interact with the Froala Editor integrated into the TMS WEB Core application.
    3. Inspect the Code: Once the demo is running, you can inspect the code to understand how the TMSWEBFroalaEditor component is being used. This can provide valuable insights and help you integrate the Froala Editor into your own TMS WEB Core projects.

Understanding the Source Code

By exploring the demo, you’ll get a better understanding of how to use the TMSWEBFroalaEditor component and integrate the Froala Editor into your own TMS WEB Core Delphi applications. The demo serves as a helpful starting point and reference for your own implementation.

For instance, to setup your own Froala Editor, do the following

  • Declare an external function so we can use Object Pascal to create the Editor Object.
  • Create an object that links the Froala Editor events with the WEB Core event handlers.
  • Initialize the Froala Editor
var  
  FEvents: TJSObject;  
  FFroalaEditor: TJSObject;  
  function froalaEditor(s: string; jsObject: TJSObject): TJSObject; overload; external name 'new FroalaEditor';  
  
begin  
    FEvents := new([  
     'contentChanged', @HandleChanged,  
     'initialized', @HandleLoaded,  
     'focus', @HandleStartEdit,  
     'blur', @HandleEndEdit  
     ]);  
  
    FFroalaEditor := froalaEditor('div#' + ElementID,   new([  
      'toolbarInline', false,  
      'events', FEvents  
      ]));  
end;

Froala WYSIWYG HTML Editor Modes

Note the demo offers two ways to use the Froala Editor:

Classic: This is the default behavior.

Froala classic editor

Inline: Show the Editor toolbar upon content selection.

Connect any TWebLabel to the TWebFroalaEditor component to instantly make it editable in the browser.

WebLabel1.EventStopPropagation := [];  
WebFroalaEditor1.Visible := False;  
WebFroalaEditor1.InlineEditing := True;  
WebFroalaEditor1.Editor := WebLabel1;

Froala inline editor

By now, you have learned how to easily add a powerful, customizable WYSIWYG editing experience to your TMS WEB Core Delphi applications, providing your users with an intuitive and efficient way to manage content.

Live Demo

A live demo of the Froala editor integration is available at https://download.tmssoftware.com/tmsweb/demos/froalaeditor/. Explore the editor’s rich text editing capabilities and view the corresponding HTML code and triggered web core event handlers below the editor.

Conclusion

In this guide, we’ve walked through the seamless process of integrating the Froala Editor into your TMS WEB Core Delphi applications. By leveraging the powerful TMSwebFroalaEditor component, you can quickly add rich text editing capabilities to your web applications.

Integrating Froala WYSIWYG HTML Editor with TMS WEB Core allows Delphi developers to create modern, responsive web apps with an intuitive WYSIWYG interface for managing content. With features like inline editing, table manipulation, and responsive video embedding, the Froala Editor provides a top-notch user experience that will delight your end-users.

With the steps outlined in this guide, you now have the knowledge and tools to integrate the Froala Editor into your own TMS WEB Core Delphi projects. By incorporating this powerful integration, you can deliver exceptional content management capabilities and take your Delphi web applications to new heights.

Get started today and elevate your Delphi web development with the TMS WEB Core Froala Editor integration

 

How to Use Bootstrap: Set Up and Customize in Your Project

Bootstrap is one of the most popular frameworks for building responsive and modern web applications. It’s extensive, modern, and easy to learn, making it suitable for beginners and experts alike.

In this guide, you’ll learn how to use Bootstrap, from installing it through different ways to customizing it to your liking.

You’ll also explore how Bootstrap helps boost developer productivity, including its various UI components, quick setup, and compatibility with modern browsers.

Additionally, you’ll learn about React Bootstrap, a reimplementation of Bootstrap components using React. This open-source, community-maintained project is an alternate way of implementing Bootstrap in React. It’s not official Bootstrap, but it’s perfect for React apps.

When developing modern websites and applications, you should also consider using tools that go well with one another. Froala is an HTML editor that synergizes well with Bootstrap. It consists of an intuitive, SEO-friendly, and already responsive interface in addition to powerful editing tools.

Before Learning How to Use Bootstrap…

You might want a refresher on its different components, as well as how to install Bootstrap. If you’re already familiar with these, skip to the next section, where you’ll explore customizing Bootstrap CSS.

Understanding Bootstrap’s UI Components

To use Bootstrap for building responsive web apps and mobile-first styles, you make use of pre-designed, customizable UI components.

These are essentially themes or styles that you apply to plain HTML elements via the class attribute.

Once the page loads, Bootstrap will then style and design your elements according to the contents of their class attributes.

For example, you can turn a common div element into a navbar by appending the “navbar” class to it. To expand the navbar on larger screen sizes, add “navbar-expand-lg.” If you want a darker theme to it, add the “bg-dark” (as of version 5.x) class.

You can even use different styling classes for one element. Think of these components as makeup or accessories for your elements. Mix and match or use them however you like to beautify and standardize the site contents.

Ultimately, they should make your site look better and consistent across different CSS media queries or screens, including mobile devices.

Each Bootstrap CSS UI component has a specific purpose. Some are for layout, while others are for theming, form design, and individual element styling.

The Bootstrap documentation pages categorize them into the following:

Layout

These are the components that deal with organizing the DOM elements to ensure that the site contents have visual structure and responsiveness.

These usually act as styling for div elements containing elements of their own. Layout concepts include the grid system, full-width containers (which wraps site contents), and breakpoints.

Content

Content components are global styling settings for text, images, tables, and more. This means that by using content components, you can set Bootstrap’s basic styling throughout your plain JS or React projects.

For example, you can use the “img-fluid” class across your images to make them responsive without having to touch CSS properties.

Forms

As the name suggests, this type of component is responsible for styling form elements and input fields.

These UI components include text fields, floating labels, textareas, radio buttons, checkboxes, select fields, and validation classes.

Components

What the Bootstrap docs categorize as “components” refers to pre-built UI components that come with built-in styling and interactivity (e.g., hover or popover events).

Each specific component already has Bootstrap’s consistent styling and JavaScript functionality. However, you can also modify these further using utilities, helpers, and even custom CSS.

These include the bulk of Bootstrap’s components: buttons, navbars, cards, carousels, list groups, and a lot more. Bootstrap’s UI components also include JavaScript plugins such as modals, tooltips, popovers, and collapsibility.

When learning how to use Bootstrap, it's vital to understand how its components work and interact with one another. This image presents a few of these components used together to create a responsive and presentable design.

Helpers

Helpers refer to smaller classes that perform a single function. You usually use these together with other Bootstrap components.

Examples of helpers include colored links, specific component positioning (e.g., “fixed-top,” “sticky-bottom”), text truncation, visually hidden elements (for assistive technologies), and some others.

Utilities

Utilities are general-purpose styling classes for HTML elements. Unlike helpers, they have a broader, more global scope, allowing you to control styling like colors, spacing, and typography. Like helpers, they usually go together with other classes or components.

Examples of Bootstrap utilities include margins, padding, text colors, flex options, shadows, borders, sizing, and more.

Now that you’ve had a refresher, it’s time to install Bootstrap.

Installing Bootstrap

There are different methods for installing the Bootstrap CSS and JS files. Here, you’ll discover some of the most popular ones.

via compiled Bootstrap CSS and JS

You can install Bootstrap by downloading its ready-to-use codes that include both compiled and minified Bootstrap CSS bundles and JavaScript plugins.

Note that this method does not include documentation, source files, or optional JS dependencies like Popper.

To install Bootstrap via compiled CSS and JavaScript, click here. Include the files that you need in your JS or React app’s folder afterwards. Whether you’re using React or a non-framework setup, the steps for this method are generally the same.

via the Bootstrap CDN

A quick alternative installation method for Bootstrap is by using the Bootstrap CDN. This method allows you to call a cached version of Bootstrap in your plain JS or React application.

This helps you get started faster and more easily. To add the framework through Bootstrap CDN, include the following code in your index.html file:

<head>
<!--other head items-->
...
<!--Bootstrap 5 CSS-->
<link  href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>

<body>
<!--other body items-->
<!--Bootstrap 5 JavaScript-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
</body>

This gives you the latest delivered version. You can also specify which version of Bootstrap you want in your project by replacing the version number.

If you want to import Popper, jQuery, and other dependencies, you can add them before the JavaScript link through the Bootstrap CDN as well.

via Package Manager

The last installation method is installing the Bootstrap packages using NPM. To install the Bootstrap NPM package, you must have both Node.js and NPM.

To get started, open your CLI, go to your project directory, and run the following command:

npm install [email protected]

This installs the 5.3.3 version of the Bootstrap NPM package in the “node_modules” folder. This makes it available (but not yet usable; we’ll discuss this soon) for your JS or React application.

Should you need more Bootstrap 5 components, add them after the keyword. For example, run the following command to install Bootstrap with jQuery and Popper:

npm install [email protected] jquery popper.js

You should then see the NPM package’s dependencies in your package.json file. For instance, for a React app, here’s what your package.json file should look like:

An example of Bootstrap dependencies in a React app.

If you’re not using a framework, you’ll generally include the Bootstrap files in your HTML pages, similar to the code below.

<head>
<!--other head items-->
...
<!--Bootstrap 5 CSS-->

<!--If you installed Bootstrap via NPM, use the "node_modules" directory. Otherwise, replace "node_modules" with the path to your Bootstrap CSS-->
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">

</head>

<body>
<!--other body items-->
<!--Bootstrap 5 JavaScript-->
<script src="node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</body>

With this, you should have the ability to use Bootstrap’s components throughout your HTML page (and other pages that use it).

On the other hand, for a React app, import Bootstrap by adding the following code to your “src/index.js” file:

import 'bootstrap/dist/css/bootstrap.min.css';
import "bootstrap/dist/js/bootstrap.bundle.min";

This allows you to use Bootstrap components throughout your React app. Now, let’s dive into styling and customizing your projects using Bootstrap’s grid system and other components.

Basic Customization

To understand Bootstrap’s customization capabilities, let’s look into using its grid layout system, color styling, and font styling.

How to Use Bootstrap’s Grid System

The grid system is a way of laying out HTML elements in terms of rows and columns. By doing so, you ensure that each component containing elements is properly displayed with respect to each other.

Each row takes up its parent’s entire width and has a total of 12 columns, which you can divide in any way you like. For example, if you want three equal-sized columns for a row, you have to change their size to 4 (3 columns x 4 column size = 12 total columns).

On the other hand, each column can have one or more rows. You can also nest these rows and columns together.

Now, let’s test it out by creating a page with a few rectangles. Try creating some rows and dividing them into columns of varying widths. To discern them from each other, add some background colors as well.

To get started, open your file (in this case, index.html) and add the following code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>How to Use Bootstrap</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>

<body>
    <div class="container-fluid bg-light vh-100">
 <div class="row h-25">
            <div class="col border border-danger text-center">
                col-12
            </div>
        </div>
 <div class="row h-25">
            <div class="col-md-6 border border-danger text-center">
                col-6
            </div>
            <div class="col-md-6 border border-danger text-center">
                col-6
            </div>
        </div>
 <div class="row h-25">
            <div class="col-md-8 border border-danger text-center">
                col-8
            </div>
            <div class="col-md-2 border border-danger text-center">
                col-2
            </div>
            <div class="col-md-2 border border-danger text-center">
                col-2
            </div>
        </div>
 <div class="row h-25">
            <div class="col-md-2 border border-danger text-center">
                col-2
            </div>
            <div class="col-md-2 border border-danger text-center">
                col-2
            </div>
            <div class="col-md-2 border border-danger text-center">
                col-2
            </div>
            <div class="col-md-2 border border-danger text-center">
                col-2
            </div>
            <div class="col-md-2 border border-danger text-center">
                col-2
            </div>
            <div class="col-md-2 border border-danger text-center">
                col-2
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
</body>
</html>

First, add Bootstrap (in this case, through Bootstrap CDN). Next up, create a div element with the class “container-fluid,” which wraps site contents in a full-width container.

If you prefer something narrower than a full-width container, use “container” instead.

We also add the “bg-light” and “vh-100” classes to the wrapper. The former is simply for adding a touch of color, while the latter makes the container span the entire height of the screen.

Afterwards, create four rows of equal height (“h-25” allows a row to take up a fourth, or 25%, of the parent element’s height).

Finally, create as many as twelve columns for each row. How you divide it is up to you, but in the example above, you have:

  • 1-column row: The first row only has one column. You can use either “col” or “col-12” to allow a column to take up the entire width of the row.
  • 2-column row: The second row has two equal-length columns. Hence, each column has the “col-md-6” class.
  • 3-column row (unequal lengths): The third row has three columns of varying sizes. The first one is longer (8 columns long), while the other two have an equal length of 2.How you divide the row is up to you, but the total columns per row should be 12.
  • 6-column row: The fourth row has six columns of size 2.

To better discern the columns, add a border to each of them by appending the “border border-danger” classes.

The “border” (as the name suggests) class adds a border to an element, while the “border-danger” one adds Bootstrap’s red theme color to it.

Run the application, and you should see the following screen:

A sample application powered by Bootstrap. This screen contains 4 rows with different columns each. All columns have a reddish border color from Bootstrap's border-danger class.

Now, let’s try customizing Bootstrap’s default colors and fonts with some custom CSS.

How to Customize Colors and Fonts

You can override Bootstrap’s default settings with custom CSS and Bootstrap 5.

Bootstrap 5 defines prebuilt CSS variables (–bs-*) for colors, typography, spacing, and more. These variables make overriding Bootstrap styles easier without modifying Bootstrap’s core files.

Overriding these CSS variables changes all elements that use Bootstrap’s default styles to follow your theme, colors, and fonts.

For instance, create a CSS file, include it in your HTML, and insert the following lines of code:

:root {
    --bs-light: #eeeeee;
    --bs-danger: #01a4f9;
    --bs-body-font-family: 'Roboto', sans-serif;
}

.bg-light {
    background-color: var(--bs-light) !important;
}

.border-danger {
    border-color: var(--bs-danger) !important;
}

The code above defines some CSS variables (e.g., –bs-light) for changing the colors of the “light” and “danger” properties. Moreover, it also changes the default font into “Roboto.”

Note that the colors this code is using are significantly different from the default (whitish gray to slightly darker gray, red to light blue).

Afterwards, the code uses these CSS variables for the “background-color” and “border-color” properties. Now, if you run the application, you should see:

In our grid example, the border color has changed into a lighter shade of blue. Additionally, the background color is now a darker gray, and the font family is different.

In addition to colors and fonts, you can also use CSS to customize buttons, navbars, forms, dropdown menu, and other components by using the “!important” keyword. This overrides Bootstrap’s default properties.

In summary, to integrate your color scheme and typography, define CSS variables to change the default colors and fonts to your theme’s. Afterwards, you can use these variables across your CSS file together with the “important” keyword.

Now, let’s move into the more advanced Bootstrap customization techniques.

Advanced Customization Techniques

If you want to go beyond basic CSS customization for Bootstrap, you should try using both Bootstrap JS plugins and Sass.

JS plugins add a bit of animation and interactivity to your components, improving the UX. Sass, on the other hand, provides a more organized way of customizing styles, making it perfect for theming.

Modifying Bootstrap Components with Sass

Sass (Syntactically Awesome Stylesheets) is a CSS preprocessor that allows you to write cleaner styles more efficiently. The Bootstrap framework is built on Sass, which means that you can easily customize its components and styles to match your needs.

The best part is you don’t have to manually override styles using CSS like we did in the previous section.

Note: Sass requires that you get the entire library using NPM or local installation. Bootstrap Sass won’t work if you’re using the CDN.

Let’s start setting up Sass. First, go to your project directory and run the following line:

npm install -g sass

This command installs the Sass compiler in your directory, allowing you to use Sass commands.

Afterwards, create a new folder in your root and name it “scss” or something similar. In this new folder, create a file called “custom.scss.”

Here, you’re creating your own stylesheet that imports Bootstrap instead of modifying Bootstrap’s core files. This is because Bootstrap does not recommend modifying its core files.

Open your “custom.scss” file and add the following lines:

$light: #eeeeee;
$danger: #28a745;

$font-family-base: 'Roboto', sans-serif !default;

@import "../node_modules/bootstrap/scss/bootstrap";

Here, you’re defining new colors for the “light,” “danger,” and “font-family-base” CSS properties. This step is similar to what you did in the previous section, albeit easier. This code also uses a different “danger” color from earlier.

Lastly, import the Bootstrap components at the end of the SCSS file. Bootstrap recommends importing only what you need, but for simplicity, the code above imports the entire library.

Afterwards, in your CLI, move up to the “scss” folder and run the following line:

sass custom.scss custom.css

This command essentially tells the Sass compiler to compile our “custom.scss” file into CSS, specifically with the filename “custom.css.” Afterwards, you should see the newly generated “custom.css” file in your “scss” folder.

For the next step, since you’re creating your own stylesheet that imports Bootstrap, you won’t need the Bootstrap CSS link in your HTML file anymore. In your index.html, replace the head contents with:

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Sample Bootstrap App</title>
    <!--<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">-->
    <!--<link href="styles.css" rel="stylesheet">-->
    <link rel="stylesheet" href="scss/custom.css">
</head>

Note that the previous links (to the Bootstrap files and the custom stylesheet) are now commented so that you can use the new CSS file that you compiled from SCSS beforehand.

Run the application, and you should see the following changes:

After creating an SCSS file, compiling it into CSS, and using it, we are able to achieve the same effect of customizing Bootstrap, but in an easier manner.

Using Bootstrap’s JavaScript Plugins

Bootstrap provides different JavaScript plugins to add interactivity and animation to your projects. These JS plugins include:

  • Modal: These are pop-up dialogs that you can use to display information, policies or terms of use, and forms. These usually include a title, body, and footer.
  • Tooltips & Popovers: Plugins that show additional information on mouse hover (tooltips) or click (popovers). These can have either only text or a pair of title and text.
  • Toast: Use these when you want to display stylized notifications easily. These also typically include a header and a body.
  • Collapse: Plugins that create toggleable elements. These keep the application looking clean, hiding and showing elements that could clutter the display on smaller screens.
  • Carousel: These are responsive image sliders. They usually come with a title, body, image, and a pair of “next” and “previous” buttons for going through the media files.

Let’s try using a tooltip and popover. In your index.html file, pick any column from any row and add the following lines of code:

<button type="button" class="btn btn-danger text-white" data-bs-container="body" data-bs-toggle="popover" data-bs-placement="top" data-bs-content="This popover appears at the top of the button.">
     Click Me!
</button>

<button type="button" class="btn btn-info text-white" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-title="This tooltip appears at the right side of the button.">
     Hover over me!
</button>

This code adds two buttons: one for triggering the popover event and another for the tooltip event. Specify the type of data toggle using the “data-bs-toggle” property, then specify the placement of the tooltip and popover.

Afterwards, after the Bootstrap script near the bottom of the body, add the following lines:

<script>
        const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]');
        const popoverList = [...popoverTriggerList].map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl));

        const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
        const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
</script>

What this code does is initialize both the popover and tooltip trigger lists, enabling them for the page. Run the application to see the two new buttons that show a tooltip when hovered and a popover when clicked:

This image demonstrates Bootstrap's popover and tooltip components. It shows two buttons: one for displaying a popover on click and another for displaying a tooltip on hover.

These components are already cool, but you can take it up a notch by customizing them further using data attributes and JavaScript.

For example, you can use data attributes to change the behavior of the popover button, shown in the code below:

<button type="button" class="btn btn-danger text-white"
     data-bs-container="body"
     data-bs-toggle="popover"
     data-bs-placement="top"
     data-bs-config='{"animation": false, "delay": {"show": 500, "hide": 100}}'
     data-bs-content="This popover appears at the top of the button.">Click Me!</button>

This removes Bootstrap’s default animation for the popover. Instead, it will show the popover after 500ms without the fade-in effect. Note that to use the “data-bs-config,” you need to modify your popover and tooltip script into something like:

document.addEventListener("DOMContentLoaded", function () {
    const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]');

    popoverTriggerList.forEach((popoverTriggerEl) => {
        const config = JSON.parse(popoverTriggerEl.getAttribute("data-bs-config"));
        new bootstrap.Popover(popoverTriggerEl, config);
    });

    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    tooltipTriggerList.forEach((tooltipTriggerEl) => {
        new bootstrap.Tooltip(tooltipTriggerEl);
    });
});

On the other hand, you can use JavaScript to change the behavior of the plugins. For instance, to dynamically update the tooltip options, replace the tooltip script with:

document.addEventListener("DOMContentLoaded", function () {
            const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');

            tooltipTriggerList.forEach((tooltipTriggerEl) => {
                const tooltip = new bootstrap.Tooltip(tooltipTriggerEl);

                tooltipTriggerEl.addEventListener("mouseenter", function () {
                    tooltip.setContent({ '.tooltip-inner': "New Tooltip Text!" });
                    tooltip.update();
                });
            });
});

This code dynamically replaces the contents of the tooltip on DOM load.

That’s all we need to discuss in this article about using Bootstrap’s most common features. But before you go, why not talk about another suitable Bootstrap implementation for React apps?

React Bootstrap: An Alternative for React Apps

Bootstrap, as it is, works well with React apps. But if you want something that works more like React, then you should consider using React Bootstrap. Let’s quickly explore what it is and what makes it different below.

What is React Bootstrap?

React Bootstrap is a popular front-end framework from an open-source community. Although not officially from the Bootstrap team, it is perfect for React apps because it doesn’t rely on direct DOM manipulation.

Instead, it’s built on React components, ensuring better compatibility with React’s virtual DOM and state management. So, instead of using syntax like “<button class=’btn btn-primary’>…,” you would use something like “<Button variant=’primary’>Primary</Button>.”

Key Differences between Traditional and React Bootstrap

  • Component-based Approach: React Bootstrap provides pre-built React components like <Button> and <Form> instead of using HTML and class-based Bootstrap components.
  • No jQuery Dependency: Traditional Bootstrap requires jQuery for some interactive features or animations. On the other hand, React Bootstrap relies on React itself, reducing unnecessary dependencies.
  • Better Integration with React Apps: React Bootstrap components support props, state management, and lifecycle methods, allowing more flexibility to ensure proper rendering.

Best Practices for Using Bootstrap

Using Bootstrap is easy, even if you are a beginner. However, beginner or not, developers should always research and consider the best practices when using Bootstrap. By doing so, you can avoid future headaches like security breaches, obsolescence, and performance issues.

Here are two important things to consider for Bootstrap:

Keep Bootstrap Updated

Regularly updating Bootstrap ensures access to the latest features, performance improvements, and security patches. Outdated versions may have vulnerabilities or lack support for modern web standards.

Just be sure to check the documentation pages first before updating to the latest. Bootstrap could change some syntax on their next update, possibly breaking some existing code if not thoroughly checked. For example, “text-start” and “text-end” used to be “text-left” and “text-right” a few years ago.

Optimize Bootstrap for Performance

  • Minimize CSS and JS Files: Use only the necessary Bootstrap components by customizing builds. You can also use other third-party tools to help remove unused styles.
  • Use Only Necessary Components: As briefly stated earlier, instead of importing the entire Bootstrap library, import individual components to reduce bundle size and improve loading times.

Conclusion

And that’s it! You now have some basic understanding of how Bootstrap works. Additionally, you’re now equipped to customize it to suit your applications.

Experimenting with different customization options will help tailor Bootstrap to specific project needs.

So, how do you find Bootstrap so far? Did you play around with the different components and customization settings? Share your experiences and tips on using Bootstrap in the comments!

Adding Rich Text Editor Support For Contact Form 7 WordPress Plugin

rich-text editor for contact form 7

Would you like to allow users to submit formatted content through your Contact Form 7 forms instead of plain text? This guide explains step-by-step how you can integrate a rich-text editor for Contact Form 7 using the Froala WordPress content editor.

What Is Contact Form 7?

Contact Form 7 is one of the most popular form-building plugins used by millions of WordPress websites worldwide. It’s incredibly reliable and powerful for creating simple to advanced forms.

Contact form 7

But there’s one limitation—its default text area fields only allow plain text submissions. This means users can’t include HTML tags like bold text, italics, headings, or any other visually appealing formatting.

That’s where adding a rich text editor like Froala can greatly improve the user experience and allow your forms to accept visually engaging, formatted submissions.

Why Add a WordPress Content Editor to Contact Form 7?

By adding a rich text editor field, you’ll significantly enhance your user’s experience. Contributors to your forms will now be able to easily provide complex content using the wordpress editor. Instead of receiving boring plain text submissions, you’ll get nicely formatted messages including headings, bold text, italicized text, and lists.

This improvement can make submissions easier to read, more organized, and visually appealing, potentially boosting your engagement and conversion rates. Your WordPress site and your email communications will both look more professional and polished.

Creating a Rich Text Editor Field for Contact Form

Let’s get started! Follow these easy steps to add the feature to your form:

Step 1: Setting Up Your Contact Form

  • In your WordPress dashboard, navigate to Contact Form 7 under the plugins menu.
  • Either create a new form or select an existing contact form to edit.
  • You might already have something like this in your form template:
<label> Your name
    [text* your-name autocomplete:name] </label>

<label> Your email
    [email* your-email autocomplete:email] </label>

<label> Subject
    [text* your-subject] </label>


[submit "Submit"]

Step 2: Adding a Rich Text Editor Field for Contact Form

Now let’s add the new Froala-powered rich text editor field:

  • Click on the “textarea” button to insert a new field.

rich text wordpress content editor

  • In the “Field name” input, provide a unique identifier such as “message“.
  • In the “Class attribute” input, add a class name you’ll use later to reference the field in the Froala initialization code. A simple example is “editor“.
  • Your inserted tag will look like this:
[textarea message class:editor]

Insert text area field

  • Click “Insert Tag“, and your form template will now include this new field for complex content submission.
  • Save your updated contact form.

Initializing Froala Rich Text Editor on Your Form

You’re almost there! Next, you’ll need to set up your form emails to handle HTML content properly.

Step 3: Configuring Email Submission with HTML Tags

  • In your Contact Form 7 settings, click the “Mail” tab.
  • Ensure you’ve checked “Use HTML content type“. This setting allows your submissions to include HTML tags and maintain their formatting.
  • Also, ensure the “message” field is referenced in your “Message body“.
contact form email setup
  • Click “Save” and copy the generated shortcode provided by Contact Form 7.

Step 4: Embedding Your Contact Form into a WordPress Page

To display your new rich text-enabled form, embed the shortcode into one of your WordPress pages:

  • Open the page editor for your desired page.
  • Paste your shortcode where you want the form to appear:

Error: Contact form not found.

Insert contact form shortcode
  • Click “Publish” or “Update” to make the page live on your WordPress site.

Step 5: Adding the Froala WordPress Content Editor to the Form Page

Now, you’ll add the Froala rich text editor resources directly to your page. Simply include the Froala CDN link and initialization script:

Add these CDN references to your page or site’s HTML head:

<link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.min.css' rel='stylesheet' />
<script src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.min.js'></script>

Then initialize the Froala editor on your textarea field using the class name “editor“:

<script> document.addEventListener('DOMContentLoaded', function() { new FroalaEditor('.editor'); }); </script>
rich text editor for contact form 7

After adding this code snippet, save and publish your page.

Testing Your New Rich Text Contact Form

Now it’s time to test your implementation:

  • Open your published page in a browser.
  • You should now see your contact form with the Froala rich text editor field instead of the plain textarea.

rich-text editor for contact form 7

  • Enter test values and experiment by formatting your message with headings, bold, italics, and more.
  • Submit your form and verify the formatted HTML content appears correctly in your email inbox.

rich-text editor for contact form 7 submitted

Improving Your WordPress Submissions with Complex Content

With Froala integrated, your website visitors can now submit visually rich and complex content directly through your forms. This simple upgrade drastically improves the readability and organization of form responses. It also enhances your overall communications, making them look professional and polished.

No more monotonous plain text submissions—each submission now comes beautifully formatted and ready for immediate use, perfect for your next post.

Conclusion

By following this straightforward, step-by-step guide, you’ve successfully added a powerful rich text editor to your Contact Form 7 forms. With Froala powering your form submissions, your website’s user experience is significantly enhanced, allowing for detailed, structured, and engaging responses.

This simple yet impactful integration transforms the way your website visitors interact with your forms, providing a much-improved WordPress experience. Now go ahead and enjoy the benefits of beautifully formatted submissions!

Add Multilingual Translation to Froala with Translate Plus API from APILayer

Multilingual Translation API

As a developer, you may often need to create applications that cater to a global audience, such as chatting applications. One common challenge is overcoming language barriers by providing seamless translation capabilities to allow users from diverse linguistic backgrounds to access and engage with each other.

In this tutorial, I’ll show you how I added a powerful translation feature to my Froala Editor-based chatting application using the Translate Plus API from APILayer. This multilingual translation API integration created a truly inclusive experience for users, allowing them to communicate effectively regardless of their native language.

Translate Plus API

Exploring the Translate Plus API on the APILayer Marketplace

As I was building a new Froala editor demo for a chatting application, I needed to add high quality translations to enable users from diverse linguistic backgrounds to communicate with each other. While existing translation tools like the Google Translate API are popular, I wanted to explore alternatives that could offer accurate translations with broader language support at much cheaper price.

While exploring the APILayer marketplace, which offers a wide range of APIs to help you build modern, feature-rich applications with real-time translations, I discovered the Translate Plus API, which seemed like the perfect solution to my problem.

APILayer Marketplace

What is APILayer?

APILayer is a popular API marketplace that provides access to a wide range of APIs, not limited to translation services. It also offers APIs that integrate with the Google Cloud ecosystem and other technical content service providers.

As a developer, I appreciated the ease of integration for the APIs provided by APILayer, which made it straightforward to incorporate new features into my applications.

Why Choose APILayer?

Utilizing APILayer includes several benefits, such as:

  • Wide Variety of APIs: It offers APIs for currency conversion, IP geolocation, weather data, email validation, and much more, catering to a broad spectrum of use cases including machine translation.
  • Ease of Integration: Their APIs are designed to be user-friendly, with straightforward documentation and code samples that allows for quick and seamless integration.
  • Cost-Effectiveness: Many of their APIs are affordable and come with tiered pricing models, making it accessible for both startups and enterprises working on large scale projects.
  • Reliability: All the APIs are thoroughly reviewed for high accuracy before they are listed by the APILayer team, ensuring customer satisfaction.

Why Use the Translate Plus API?

The Translate Plus API from APILayer stood out to me as a powerful tool that could seamlessly integrate with the Froala Editor to provide translation capabilities for multiple languages. The language detection feature was particularly impressive, as it could automatically determine the source language.

One of the key features of using the Translate Plus API from the APILayer marketplace is the extensive language support. Unlike some other APIs that are limited in their support for language pairs, this service truly excels.

The Translate Plus API supports over 100 languages, catering to a diverse global audience. This flexibility enables my users to translate content into their preferred languages, ensuring that information is accessible and understandable to all, even when dealing with industry jargon or technical terms.

The comprehensive documentation and intuitive API design made it easy for me to quickly implement the translation feature in my application. Additionally, the competitive pricing and reliable performance of the Translate Plus API were key factors that influenced my decision to leverage this solution over other alternatives.

How the Translation Feature Works

I wanted to make the translation process seamless and intuitive for users. To achieve this, I aimed to add a new toolbar button to the Froala Editor. When users click this button, they’ll see a dropdown menu displaying all the languages supported by the Translate Plus API.

Users can then select their preferred language from the list. Once they make their selection, the API automatically detects the original language of the content and translates it into the user’s chosen language. The editor then instantly updates, displaying the translated text.

Froala integration with translation API

This straightforward interaction allows users to quickly and easily access content in their native tongue, fostering a more inclusive and accessible experience within the chatting application.

Integrating the Translate Plus API into the Froala Editor

Step 1: Get a Translate Plus API Key

I began by signing up for a Translate Plus account and obtaining an API key, which would be necessary for authenticating my API requests. This process was similar to what you’d experience with other APIs.

Step 2: Create a starter template

Next, I included the necessary Froala scripts and stylesheets in my HTML file. Additionally, I added an HTML element that would serve as the container for the editor. This is where the Froala editor would be rendered.

To enhance the visual appeal of the editor’s toolbar, I also included the Font Awesome 5 stylesheet. This allowed me to use the iconic Font Awesome 5 library to represent the toolbar buttons’ icons.

<!DOCTYPE html>
<html>

<head>
    <title>Froala WYSIWYG Editor</title>
    <!-- Include Froala CSS -->
    <link href="{{editor__download__folder}}/css/froala_editor.pkgd.min.css" rel="stylesheet"
        type="text/css" />
        
    <!-- Include Font Awesome 5 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.5.0/css/all.min.css" rel="stylesheet"
        type="text/css" />
</head>

<body>

    <!-- HTML element where the editor will be initialized -->
    <div id="editor">
    </div>

    <!-- Include Froala Editor JS files -->
    <script type="text/javascript" src="{{editor__download__folder}}/js/froala_editor.pkgd.min.js"></script>
 
</body>

</html>

Step 3: Get Translate Plus Supported Languages

var myHeaders = new Headers()
myHeaders.append("X-API-KEY", "b2430***************************19be00")
myHeaders.append("Content-Type", "application/json")

var requestOptions = {
  method: "GET",
  redirect: "follow",
  headers: myHeaders,
}

fetch("https://api.translateplus.io/v1/supported-languages", requestOptions)
  .then((response) => response.json())
  .then((result) => initFroala(result.supported_languages))
  .catch((error) => console.log("error", error))

To get the list of supported languages for the Translate Plus API, I made a GET request to the /supported-languages endpoint. This provided me with a comprehensive list of all the languages that the API supports. I then passed this information to the initFroala function, which I will use to create the translation toolbar button and initialize the Froala Editor.

By obtaining the full list of supported languages, I could ensure that my users would have access to a wide range of translation options, catering to diverse linguistic needs. This flexibility would be a key differentiator for my chatting application, allowing users from all over the world to communicate effectively, regardless of their native tongue.

The straightforward API documentation and intuitive response format made it easy for me to parse and utilize the language data. This streamlined the development process, allowing me to quickly move on to the next steps of creating the custom toolbar button and integrating the translation functionality.

Step 4: Create the Translation toolbar button

Now, I need to add a new custom button to the editor’s toolbar. When clicked, this button would display a dropdown menu with the list of available translation languages.

The dropdown menu would allow the user to select the desired target language for translation. When a language is selected, I would use the Translate Plus API to fetch the translated content and update the editor’s text accordingly.

Step 4.1 Define the Translation toolbar button icon

To define an icon for the translate toolbar button, I did the following:

  // Set Font Awesome 5 as the default toolbar icon library.
  FroalaEditor.ICON_DEFAULT_TEMPLATE = "font_awesome_5"

  // Set the Font Awesome's language symbole as icon for the "translate" button
  FroalaEditor.DefineIcon("translate", { NAME: "language" })

By using the recognizable language icon, I ensured that users would instantly understand the purpose of the translation button, enhancing the intuitiveness of the feature.

Step 4.2 Craft the Translation Toolbar Button

To create the new “translate” button, I defined an object with several key properties:

title

The title represents the label of the button.

title: "translate",

type

The type property defines the button’s behavior. In this case, I set it to “dropdown” since it will open a list of translation options.

type: "dropdown",

options

The options property holds an object containing the supported translation languages, which I obtained from the Translate Plus API in step 3. I can access this object later using the FroalaEditor instance at FroalaEditor.COMMANDS.translate.options.

html

The html property is a method that returns the HTML code for the dropdown menu. Here, I used the FroalaEditor.COMMANDS.translate.options object to dynamically generate a list of the supported translation languages.

    html: function html() {
      var c = '<ul class="fr-dropdown-list" role="presentation">'
      var options = FroalaEditor.COMMANDS.translate.options

      for (var val in options) {
        if (options.hasOwnProperty(val) && val!=="Auto Detect") {
          c += `<li role="presentation"><a class="fr-command fr-title" tabIndex="-1" role="option" data-cmd="translate" data-param1="${this.language.translate(options[val])}" title="${this.language.translate(val)}"> ${this.language.translate(val)} <span class="fr-sr-only">${this.language.translate(val)}</span></a></li>`
        }
      }

      c += "</ul>"
      return c
    },

callback

The callback property defines the action executed when the user selects a language from the dropdown menu.

First, I check if the editor is empty using the core.isEmpty() method. If the editor has content, I select all the text using the commands.selectAll() method and save it to a variable using selection.text().

Then, I call a translate() function, passing the selected text and the user’s chosen language as arguments. This function handles the translation process and returns the translated content. Finally, I update the editor’s content with the translated text using the html.insert() method.

callback: async function callback(cmd, param1) {
     if(this.core.isEmpty()) return;
    
      this.commands.selectAll();
      const text = this.selection.text();   
      const result = await translate(text, param1);
      this.html.insert(result.translations.translation, true);

      
    },

Step 4.3 Handling the Translation Process

The translate function receives the current content of the Froala Editor and the desired target language. It then sends a request to the Translate Plus API, passing both parameters.

Importantly, I set the source parameter to "auto". This tells the Translate Plus API to automatically detect the original language of the content. This ensures a seamless translation experience for the user, as they don’t need to worry about specifying the source language.

The API then responds with the translated content, which the translate function returns. Here’s the code:

 async function translate(text, translateTo) {
    var requestOptions = {
      method: "POST",
      redirect: "follow",
      headers: myHeaders,
      body: JSON.stringify({
        text,
        source: "auto",
        target: translateTo,
      }),
    }
    let data = false
    try {
      const response = await fetch(
        "https://api.translateplus.io/v1/translate",
        requestOptions,
      )
      // Check if the response is okay
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`)
      }

      // Parse the response JSON
      data = await response.json()
    } catch (error) {
      console.log("error", error)
    }
    return data
  }

The automatic language detection and the straightforward API response make the translation process effortless for the user, especially when dealing with context-specific content.

Step 5: Initialize The Froala Editor

Finally, I called the FroalaEditor constructor and passed an object with the necessary configurations, including the custom translation button I defined earlier.

new FroalaEditor("#editor", {
    wordCounterCount: false,
   charCounterMax: 5000,
    toolbarBottom: true,
    toolbarButtons: ["bold", "italic", "underline", "strikeThrough", "|", "formatOL", "formatUL", "|", "textColor", "backgroundColor", "fontSize", "|", "insertLink", "translate"],
  })
}

I set the charCounterMax to 5000, which is the maximum number of characters that can be translated using the Translate Plus API in one call. For larger projects, you might consider implementing batch processing to handle more extensive content.

The translation feature is now seamlessly integrated into the Froala Editor, allowing users to effortlessly translate content within the application. The custom translation button in the toolbar provides a clear and recognizable interface for users to access the translation functionality, further improving the overall usability of the editor. This feature is particularly useful for mobile apps that need to support global audiences.. Try it now.

Conclusion

By leveraging the Translate Plus API from the APILayer marketplace, I was able to add a powerful translation feature to my Froala Editor, empowering my users to consume content in their preferred languages. This integration not only enhances the functionality of my tool but also showcases the value that the APILayer marketplace can bring to developers like myself.

For companies undergoing digital transformation, incorporating translation tools like this can significantly improve customer sentiment and expand market reach. Whether you’re working with PHP, Java, Python, or other languages, the API integration process remains straightforward.

I encourage other tech-savvy developers to explore the APILayer marketplace and discover the wealth of APIs and services that can help them solve their unique challenges and enhance their projects. The Translate Plus API is just one example of the many innovative solutions available, and I’m confident that the marketplace has much more to offer.

If you’d like to try this out, you don’t need to run a git clone https command – just follow the steps above and implement the API in your own environment!

Step-by-step Guide To Add a Custom Export from Markdown Button to Froala

Custom Export Markdown Button

The Froala Markdown feature allows users to write content using a simplified markup language that is easy to read and write. This feature is important because it enables users to format their text with headings, lists, links, and other elements quickly, without needing to use complex HTML tags. Markdown’s simplicity also boosts productivity, making it a favorite among content creators and developers.

 Add a Custom Export from Markdown Button to Froala

We covered how the Markdown feature is working in previous articles:

Today, we’ll show developers how to add a custom export from markdown button. This will let users easily save their work as a markdown file while maintaining the format of their markdown document. The Froala Editor provides a powerful way to extend its functionality, making this implementation straightforward.

Why Add a Custom Export to Markdown Button?

Markdown is a lightweight markup language that has become increasingly popular among developers and writers alike. It offers a simple and efficient way to format text, making it a preferred choice for tasks such as writing documentation, creating README files, and composing blog posts. By adding a custom button to your Froala-powered application, you provide users with a seamless way to export their content in the Markdown format, enabling them to:

  • Easily share their work with others who prefer the Markdown syntax
  • Integrate their content into other tools that support Markdown
  • Maintain a clean and organized workflow by keeping their documents in a standardized format

Creating the Custom Button

Froala makes it easy to add a new toolbar button to the editor. Let’s create a custom “Export to Markdown” button step-by-step:

Step 1: Include Froala in your Project:

To include Froala in your project, follow the setup instructions in the Froala documentation according to your programming language and framework. For this demo, I only used the core Froala editor and the Markdown plugin to keep my project simple, avoiding unnecessary features. Here’s the resulting template:

<!DOCTYPE html>
<html>

<head>
    <title>Froala WYSIWYG Editor</title>
    <!-- Include Froala CSS -->
    <link href="{{editor__download__folder}}/css/froala_editor.min.css" rel="stylesheet"
        type="text/css" />
    <link href="{{editor__download__folder}}/css/plugins/markdown.min.css" rel="stylesheet"
        type="text/css" />
</head>

<body>
    <!-- HTML element where the editor will be initialized -->
    <div id="editor">
    </div>


    <!-- Include Froala Editor JS files -->
    <script type="text/javascript" src="{{editor__download__folder}}/js/froala_editor.min.js"></script>
    <script type="text/javascript" src="{{editor__download__folder}}/js/plugins/markdown.min.js"></script>
 
</body>

</html>

Step 2: Define an Icon for the Button:

With Froala, you can easily define icons for toolbar buttons. You can define the icon using one of the wide range templates Froala provides. I prefer using SVG icons. First, I’ll add the SVG path for the “Export” icon to the FroalaEditor.SVG object:

FroalaEditor.SVG.export  ="M15.293 5.293L12 8.586V2h-1v6.586L8.707 5.293 7.293 6.707 12 11.414l4.707-4.707zM18 11h-1v4H7v-4H6v5h12v-5z";

Then, I’ll register the icon using the FroalaEditor.DefineIcon method:

FroalaEditor.DefineIcon("export", { NAME: "Export", SVG_KEY: "export" });

Step 3: Define the Custom Button:

To create the new “Export to Markdown” button, I’ll define a new object with the following properties:

title

The title represents the label of the button. It is set to “Export from Markdown”.

title: "Export from Markdown",

type

Defines whether this is a button or a dropdown. In this case, it is set as a button.

type: "button",

plugin

Associate the button with a specific plugin. Here, it is linked to the Markdown plugin.

plugin: "markdown",

undo

Since the button’s function doesn’t need to be added to the undo stack, this is set to false.

undo: false,

showOnMobile

To make the button visible on mobile devices, this is set to true.

showOnMobile: true,

disabled

Determines the initial state of the button—whether it should be disabled or enabled. Since the button should only be available when the editor is in Markdown mode, I set it to true.

disabled: true,

refreshAfterCallback

When set to true, the editor will refresh all toolbar buttons after the button’s callback is executed.

refreshAfterCallback: true,

refresh

Defines the function executed during the toolbar button refresh process. The button is initially disabled, I will utilize this function to enable the button when the Markdown feature is active. I will use themarkdown.isEnabled() method to check the state of the Markdown feature:

  • If true, I will enable the button.
  • If false, I will disable the button.
  refresh: function refresh($btn) {
    if (this.markdown.isEnabled()) $btn[0].classList.remove("fr-disabled").setAttribute('aria-disabled', 'true');
    else $btn[0].classList.add("fr-disabled").setAttribute('aria-disabled', 'false');
  },

forcedRefresh

To ensure the button’s refresh method is triggered whenever the user clicks any toolbar button, forcedRefresh is set to true.

forcedRefresh: true,

Callback Function

Defines the action executed when the button is clicked. In this case, it handles Markdown export, allowing users to save their content as a downloadable .md file.

Steps to Export Markdown

Markdown feature

Follow these steps to enable users to export content from the Froala Editor in Markdown format. This process involves retrieving the editor content, creating a Markdown file, and providing a seamless download option via a custom toolbar button.

1. Retrieve Editor Content

To obtain the content in Markdown format:

  • Use commands.selectAll() to select all text.
  • Extract the text with selection.text().
  • Ensure the cursor position remains unchanged using selection.save() and selection.restore().
    this.selection.save();
    this.commands.selectAll();
    const markdownContent = this.selection.text();
    this.selection.restore();

2. Create a File with Markdown Content

  • Utilize the Blob constructor to create a file.
  • Set the type to text/markdown;charset=utf-8.
  • Generate a downloadable URL using URL.createObjectURL().
    const blob = new Blob([markdownContent], {
      type: "text/markdown;charset=utf-8",
    })
    const url = URL.createObjectURL(blob)

3. Download the File

  • Create an <a> element and assign the Blob URL.
  • Set the download attribute to specify the filename.
  • Trigger a click event to start the download.
  • Use URL.revokeObjectURL(url) to release the memory.
    const a = document.createElement("a")
    a.href = url
    a.download = "markdown.md"
    a.click()
    URL.revokeObjectURL(url)

Step 4: Register the Custom Button:

With the button object defined, I’ll use the FroalaEditor.RegisterCommand method to register it as a custom button.

FroalaEditor.RegisterCommand("export", {
  title: "Export from Markdown",
  type: "button",
  undo: false,
  refreshAfterCallback: true,
  forcedRefresh: true,
  disabled: true,
  plugin: "markdown",
  showOnMobile: true,
  refresh: function refresh($btn) {
    if (this.markdown.isEnabled()) $btn[0].classList.remove("fr-disabled").setAttribute('aria-disabled', 'true');
    else $btn[0].classList.add("fr-disabled").setAttribute('aria-disabled', 'false');
  },
  callback: function () {
    this.selection.save();
    this.commands.selectAll();
    const markdownContent = this.selection.text();
    this.selection.restore();
    const blob = new Blob([markdownContent], {
      type: "text/markdown;charset=utf-8",
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = url
    a.download = "markdown.md"
    a.click()
    URL.revokeObjectURL(url)
  },
})

Step 5: Initialize the Froala Editor:

Now I’m ready to initialize the Froala Editor and display it to the users.
new FroalaEditor('#editor');

6. Add the Custom Button to the Froala Toolbar:

To make the custom button available in the Froala toolbar, add it to the toolbarButtons configuration option:

new FroalaEditor('#editor', {
 toolbarButtons: ["bold", "italic", "underline", "markdown", "|", "export"],
 });

This adds the “Export to Markdown” button to the Froala toolbar alongside other buttons. When users click it, their markdown document will be downloaded as an .md file to their device. See the code in action.

Benefits of Adding the Custom Button

Integrating a custom “Export to Markdown” button into your Froala-powered application offers several benefits:

  1. Increased Flexibility: Users can easily export their content in the Markdown format, which is widely supported by various platforms. This allows them to write content once and use it across multiple systems.
  2. Improved Workflow: By providing a way to export to Markdown, you’re streamlining your users’ workflow. They can focus on content creation, knowing they can easily export their work in the desired format.
  3. Enhanced User Experience: The addition of the custom button enhances the overall user experience. Being able to convert and download their work directly from the editor saves time and reduces the need to copy/paste between applications.

Additional Customization Options

You can further enhance this functionality to:

  • Allow users to specify a filename before download
  • Add support for exporting to other formats like HTML file or PDF file
  • Include syntax highlighting in the exported code blocks
  • Apply custom CSS to the markdown editor
  • Add options to import content from external sources

Integrating with External Services

Beyond basic exporting, you can extend your Markdown functionality to integrate with popular development platforms:

GitHub Integration

Adding GitHub integration to your custom Markdown export button allows users to directly push their content to repositories. This is particularly useful for teams working on documentation or README files. You can implement a workflow that lets users select a target repository, specify the file path, and upload their markdown content with a single click from the editor.

Document Storage Solutions

For teams that need more robust document management, you can integrate with various storage solutions to help users organize their markdown files. This allows for better version control and collaboration. When implementing this feature, consider how search functionality could enhance the user experience, making it easier to find and reuse previously created content.

eBook Publishing Extensions

For content creators who want to publish longer-form content, adding EPUB export capabilities can be valuable. This feature allows users to convert their markdown documents into properly formatted eBooks that can be rendered on various devices. The process involves converting markdown to HTML and then packaging it with the necessary metadata into an EPUB file, complete with custom CSS styling.

By implementing these extensions, you provide users with a complete solution for their content creation and publishing needs, reducing the need to switch between multiple applications and streamlining their workflow across multiple pages of content.

Advanced Editor Configurations

Take your Markdown editing experience further with advanced configurations. Customize the textarea for better usability, implement additional command options, and enhance functionality to cater to specific Markdown editing needs.

Custom Textarea Enhancements

When working with Markdown in Froala, you can customize how the textarea appears and functions to make editing more comfortable. This includes adjusting the default appearance, implementing custom keyboard shortcuts, and defining specialized editing behaviors for markdown-specific syntax.

Supporting Additional Command Options

Enhance your export functionality by adding additional command options that give users more control. These could include the ability to insert predefined templates, search within the markdown content, or generate an index of headings. Each command can be configured to process the markdown in different ways depending on the user’s needs.

Conclusion

In this blog post, you’ve learned how to add a markdown button to the Froala WYSIWYG HTML Editor. By leveraging Froala’s customization features, you can easily extend the editor’s functionality to meet specific needs. This enhancement allows users to seamlessly export their markdown content as a file, improving their document management workflow.

The process demonstrates how toolbar buttons can be defined, customized, and integrated into the Froala editor, showcasing its flexibility as a powerful and extensible text editor. Implement this feature in your Froala-powered application to give users more control over their content.

Building a Note-Taking App with Flask, Froala & DeepSeek API in 30 Mins

Hey everyone! Earlier, I shared a general guide on Deepseek API Integrations in web apps. This time, I want to walk you through how I used DeepSeek API for note taking apps itself to build a simple yet modern note-taking app with Flask, Froala, and (of course) DeepSeek AI—all in just 30 minutes.

Spoiler: Yes, DeepSeek AI actively helped me build this! I used prompt engineering to have it generate boilerplate Flask code, give suggestions on how to integrate Froala, and even refine my Python functions. If you’re a developer looking for a quick and functional starting point with a sleek design, this tutorial (and DeepSeek) has you covered. Let’s dive in!

What We’re Building

We’ll create a note-taking app where users can:

  1. Write and format notes using the Froala WYSIWYG editor.
  2. Save notes to a local JSON file (simple, lightweight storage).
  3. Use DeepSeek’s API Integration to generate suggestions or improve their notes (e.g., “Help me summarize this note” or “Make this note more concise”).

The app will have a modern Material UI design with the help of the Materialize CSS framework. Everything will reside in a single app.py file for simplicity.

How I Used DeepSeek to Build It

1. Creating a Starter Flask App

I started by asking DeepSeek for a simple Flask starter app. Here’s a condensed version of my prompt:

Prompt to DeepSeek AI:
“Help me create a starter Flask app with a single route that returns a home page. Please use Python best practices, and initialize a JSON file if it doesn’t exist.”

DeepSeek responded with a skeleton code snippet, which I adapted. It even reminded me to handle the case where the JSON file might not exist.

2. Integrating the Froala Editor

Once my Flask starter was in place, I wanted to embed the Froala WYSIWYG editor into my front end. I asked DeepSeek:

Prompt to DeepSeek:
“Show me how to integrate the Froala Editor into a Flask template with Materialize CSS. I want a minimal example that includes a text editor and a button to save the content via a POST request.”

DeepSeek returned a neat HTML snippet that used both Froala and Materialize CSS from CDN links. With just a bit of tweaking, it fit perfectly into index.html.

3. Hooking Up DeepSeek for AI-Powered Notes

Finally, I wanted to let users improve or summarize their notes with AI. I asked DeepSeek:

Prompt to DeepSeek:
“How do I make a POST request to my own Flask route and then call the DeepSeek Chat API with the user input? Include an example of the JSON payload and how to handle the response in Flask.”

DeepSeek walked me through constructing the API request, including the headers and payload. It also showed me how to process the result and return it back to the client.

Let’s Build It: Step-by-Step Code

Below is the final, consolidated code. I’ve included the relevant DeepSeek calls, which you can adapt as needed.

Prerequisites

  • Python installed.
  • Flask installed (pip install flask).
  • A DeepSeek API key (get one from their website).
  • Basic knowledge of Flask and HTML.

Step 1: Setting Up Flask

Create a file called app.py and add the following code:

 

from flask import Flask, render_template, request, jsonify
import json
import os
import requests

app = Flask(__name__)

# DeepSeek API endpoint and key
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
DEEPSEEK_API_KEY = "yourapikey_here"

# File to store notes
NOTES_FILE = "notes.json"

# Ensure the notes file exists
if not os.path.exists(NOTES_FILE):
    with open(NOTES_FILE, "w") as f:
        json.dump([], f)


@app.route("/")
def home():
    return render_template("index.html")

 

This creates:

  • A simple Flask app with a / route pointing to index.html.
  • A local JSON file called notes.json to store your notes.
  • Variables for the DeepSeek API URL and key.

(DeepSeek’s suggestion helped me remember to handle the file check gracefully.)

Step 2: Adding the Froala Editor and Materialize CSS

Inside a templates folder, add index.html with the following code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Note-Taking App</title>
    <!-- Materialize CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
    <!-- Froala Editor CSS (using the official CDN) -->
    <link href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel="stylesheet"
        type="text/css" />
</head>

<body>
    <div class="container">
        <h1 class="center-align">My Note-Taking App</h1>
        <div class="row">
            <div class="col s12">
                <!-- Froala Editor Target (using a DIV as recommended) -->
                <div id="froala-editor"></div>
            </div>
        </div>
        <div class="row">
            <div class="col s12">
                <button class="btn waves-effect waves-light" onclick="saveNote()">
                    Save Note
                </button>
                <button class="btn waves-effect waves-light" onclick="askDeepSeek()">
                    Improve Note with DeepSeek
                </button>
            </div>
        </div>
        <div class="row">
            <div class="col s12">
                <h3>Saved Notes</h3>
                <ul id="notes-list" class="collection"></ul>
            </div>
        </div>
    </div>

    <!-- jQuery (if you need it for other parts of your app) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <!-- Materialize JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <!-- Froala Editor JS -->
    <script type="text/javascript"
        src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js"></script>

    <script>
        // Global variable to hold the editor instance
        let editorInstance;

        // Initialize Froala using the constructor API when the DOM is ready
        document.addEventListener("DOMContentLoaded", function () {
            if (typeof FroalaEditor === "function") {
                editorInstance = new FroalaEditor("#froala-editor", {
                    // Optional configuration options go here.
                });
                loadNotes();
            } else {
                console.error("FroalaEditor is not loaded correctly.");
            }
        });

        // Save note to server using the editor instance API
        function saveNote() {
            // Use the Froala Editor instance to get HTML content.
            const content = editorInstance.html.get();
            console.log("Saving note:", content);
            fetch("/save_note", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ content: content }),
            })
                .then((response) => response.json())
                .then((data) => {
                    alert("Note saved!");
                    loadNotes();
                })
                .catch((error) => {
                    console.error("Error saving note:", error);
                });
        }

        // Ask DeepSeek for AI suggestions using the editor instance API
        function askDeepSeek() {
            const content = editorInstance.html.get();
            console.log("Sending note to DeepSeek:", content);
            fetch("/ask_deepseek", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ content: content }),
            })
                .then((response) => response.json())
                .then((data) => {
                    // Update the editor content with the response from DeepSeek
                    editorInstance.html.set(data.response);
                })
                .catch((error) => {
                    console.error("Error with DeepSeek:", error);
                });
        }

        // Load saved notes from the server
        function loadNotes() {
            fetch("/get_notes")
                .then((response) => response.json())
                .then((data) => {
                    const notesList = $("#notes-list");
                    notesList.empty();
                    data.forEach((note) => {
                        notesList.append(
                            `<li class="collection-item">${note.content}</li>`
                        );
                    });
                })
                .catch((error) => {
                    console.error("Error loading notes:", error);
                });
        }
    </script>
</body>

</html>

 

 

This integrates:

  • Froala Editor for rich text editing.
  • Materialize CSS for a modern look and feel.
  • Buttons for saving notes and asking DeepSeek for improvements.
  • A list (<ul>) that displays all the saved notes.

Step 3: Adding Backend Logic (Saving Notes + DeepSeek)

Finally, we add routes to save notes, retrieve them, and request help from DeepSeek. In app.py, place the following below the existing code:

@app.route("/save_note", methods=["POST"])
def save_note():
    data = request.json
    with open(NOTES_FILE, "r") as f:
        notes = json.load(f)
    notes.append({"content": data["content"]})
    with open(NOTES_FILE, "w") as f:
        json.dump(notes, f)
    return jsonify({"status": "success"})


@app.route("/get_notes", methods=["GET"])
def get_notes():
    with open(NOTES_FILE, "r") as f:
        notes = json.load(f)
    return jsonify(notes)


@app.route("/ask_deepseek", methods=["POST"])
def ask_deepseek():
    data = request.json
    # Modify the prompt to instruct the API to return only the improved note text.
    prompt = f"Return only the revised note: {data['content']} dont add any ** ** or any formatting that would look weird just return it with plain text"

    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": "deepseek-chat",
        "messages": [
            {"role": "user", "content": prompt}
        ]
    }

    response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload)
    if response.status_code == 200:
        return jsonify({"response": response.json()["choices"][0]["message"]["content"]})
    else:
        return jsonify({"response": "Error contacting DeepSeek API."})

 

Here’s what’s happening:

  1. /save_note: Takes the note from the user, loads existing notes from notes.json, appends the new note, and saves it back.
  2. /get_notes: Returns the JSON array of all saved notes.
  3. /ask_deepseek:
    • Prepares a prompt by adding the user’s note content.
    • Calls the DeepSeek API with the user’s text.
    • Returns the AI-generated response to the front end.

(DeepSeek initially gave me the code in smaller pieces, and I combined them into one final function.)

Step 4: Run and Test the App

Save all files.

In your terminal, run:
python app.py

Open your browser and go to:

http://localhost:5000

You’ll see your new note-taking app, with a WYSIWYG editor and buttons to save or improve your notes with AI.

Sample Prompts to Try

  • “Help me summarize this note”
    For instance:
    “I need to buy groceries. I want apples, bananas, and bread.”
    DeepSeek might return a concise list like:
    “Grocery list: apples, bananas, bread.”
  • “Make this note more concise”
    Takes a lengthy paragraph and returns a more streamlined version.
  • “Rewrite this note with a friendlier tone”
    Makes an abrupt list or instructions sound more inviting.

Lessons Learned (Thanks to DeepSeek)

  • Prompt Engineering: The better your prompt, the more helpful DeepSeek is. Experiment with “Rewrite,” “Summarize,” “Shorten,” or “Explain like I’m 5.”
  • Rapid Prototyping: Generating boilerplate code quickly lets you focus on logic instead of syntax.
  • UI Integration: Materialize + Froala looks elegant with very little CSS or JavaScript overhead.

Final Thoughts

In just 30 minutes—with a bit of help from DeepSeek—I built a modern, AI-powered note-taking app. The synergy of Flask for quick server setup, Froala for rich text editing, Materialize for design, and DeepSeek for AI suggestions made the experience seamless.

Here’s what it looks like when you run it in your local browser:

Ready to customize your app further? Here are some ideas:

  • Add user authentication for private note-taking.
  • Tag or categorize notes for organization.
  • Search capabilities with DeepSeek’s semantic understanding.

If you haven’t tried DeepSeek yet, give it a shot—it’s a powerful addition to your dev toolkit. Let me know in the comments or on social media if you build something cool.

Guide to DeepSeek API Integration: What It Is and How to Get Started

As the Product Marketing Manager for Froala, I frequently evaluate innovative tools that might empower our users, partners, and developer community. One such tool that’s been creating buzz is DeepSeek API. If you’ve ever wondered what it can do and how it works, this guide will walk you through everything you need to know—from generating your API key to handling multi-turn conversations.

But before we begin, let’s talk about why we at Froala are excited about DeepSeek. Because it’s an API-based solution, there are countless opportunities to integrate it with text editors like Froala—though here, I’ll keep that part short and sweet. This is primarily about helping you understand DeepSeek’s core functionality and how to make the most of it.

Key Takeaways

  • AI-Powered Capabilities: DeepSeek API offers advanced natural language understanding and content generation.
  • Easy Integration: It’s an API-based solution that can be seamlessly integrated with platforms like Froala Editor.
  • Step-by-Step Setup: The guide walks you through obtaining an API key, setting up your environment, and making your first API call.
  • Multi-Turn Conversations: It supports maintaining context across interactions, ideal for chatbots and dynamic conversations.
  • Robust Error Handling: Provides best practices for managing errors and experimenting with various prompt types.

What Is DeepSeek API Integration?

Before diving into technical details, let’s clarify what DeepSeek API is all about. At its core, DeepSeek API allows you to integrate advanced AI capabilities—think natural language understanding, content generation, and multi-turn conversational support—without needing to develop those machine learning models yourself.

For example, if you’re building a chatbot or a recommendation engine, DeepSeek can handle the heavy lifting behind the scenes. You simply send it prompts or data, and it returns AI-generated insights or text. This can be a game-changer for developers who want to incorporate AI features in their apps, sites, or even editors, without reinventing the wheel.

Step 1: Setting Up Your Environment

Getting started with DeepSeek API is easier than it might sound. Let’s begin by preparing your environment.

  1. Get Your API Key
    Your first move is to sign up on the DeepSeek website and generate an API key. This key is your gateway to all of DeepSeek’s endpoints and services, so keep it safe and don’t share it publicly.

  2. Install Required Libraries
    If you’re using Python, you’ll likely need requests to make HTTP calls. Install it via:

    pip install requests

    Working in another language? Check the DeepSeek documentation for recommended libraries and setups.

Step 2: Making Your First API Call

Now that your environment is ready, it’s time to interact with DeepSeek for the first time. Below is a simple Python script demonstrating how to send a user prompt to DeepSeek and retrieve the AI-generated response.

import requests

# Replace with your actual API key
api_key = "your_api_key_here"

# Define the API endpoint
url = "https://api.deepseek.com/v1/chat/completions"

# Set up the headers
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

# Define the prompt data
data = {
    "model": "deepseek-chat",
    "messages": [
        {"role": "user", "content": "Tell me a fun fact about space."}
    ]
}

# Make the API call
response = requests.post(url, headers=headers, json=data)

# Print the response
if response.status_code == 200:
    print(response.json()['choices'][0]['message']['content'])
else:
    print(f"Error: {response.status_code}")

What’s happening here?

  • We specify our endpoint and provide the necessary headers (API key, content type).
  • We define a messages array that includes a “user” message: in this example, we ask the AI to share a fun fact about space.
  • Once the request completes, we print out the AI’s response.

Step 3: Understanding the Response

When DeepSeek responds, you’ll typically receive a JSON object. Here’s an example of what that might look like:

{
  "id": "chatcmpl-12345",
  "object": "chat.completion",
  "created": 1698765432,
  "model": "deepseek-chat",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Did you know that a day on Venus is longer than a year on Venus? It takes 243 Earth days to rotate once but only 225 Earth days to orbit the Sun!"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 30,
    "total_tokens": 40
  }
}

Here’s a quick breakdown:

  • id: A unique identifier for the API request.
  • model: Specifies which AI model was used to generate this response.
  • choices: The heart of the response. Each choice includes the AI-generated message content. In our example, it’s an interesting fact about Venus.
  • usage: Useful if you’re on a paid plan, since it details how many tokens were used for both the prompt and the completion.

Step 4: Building a Conversation (Multi-Turn)

One of the most powerful features of DeepSeek is its ability to maintain context over multiple turns in a conversation. If you’re building something like a chatbot or interactive tutorial system, this is where things get really interesting.

Example: Multi-Turn Conversation

import requests

# Initialize the conversation
conversation = [
    {"role": "user", "content": "Hi, can you help me with some science questions?"}
]

# First API call
response = requests.post(
    url,
    headers=headers,
    json={"model": "deepseek-chat", "messages": conversation}
)

# Extract assistant's reply
assistant_reply = response.json()['choices'][0]['message']['content']
print(f"Assistant: {assistant_reply}")

# Add the assistant's reply to the conversation
conversation.append({"role": "assistant", "content": assistant_reply})

# User's next message
user_message = "Sure! What’s the speed of light?"
conversation.append({"role": "user", "content": user_message})

# Second API call
response = requests.post(
    url,
    headers=headers,
    json={"model": "deepseek-chat", "messages": conversation}
)

# Extract and print assistant's reply
assistant_reply = response.json()['choices'][0]['message']['content']
print(f"Assistant: {assistant_reply}")

In this snippet:

  • We start with a user message.
  • We send it to DeepSeek, capture the “assistant” reply, and then add that reply back into our ongoing conversation list.
  • The conversation object grows over time, giving the AI the context it needs to respond in a natural, conversational way.

Step 5: Handling Errors

Even well-designed APIs can throw errors due to invalid keys, downtime, or other issues. Here’s a quick way to handle potential pitfalls:

try:
    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status()  # Raises an exception for bad status codes
    print(response.json()['choices'][0]['message']['content'])

except requests.exceptions.HTTPError as err:
    print(f"HTTP error occurred: {err}")

except Exception as err:
    print(f"An error occurred: {err}")

This approach ensures your application can gracefully manage unexpected scenarios without crashing.

Step 6: Experimenting with Prompts

To truly harness the power of DeepSeek, you’ll want to explore various prompts. Here are a few ideas to get your gears turning:

  • Content Generation:
    Prompt: “Write a short blog post about the benefits of remote work.”
  • Code Assistance:
    Prompt: “Explain how to use Python’s map() function with an example.”
  • Creative Writing:
    Prompt: “Write a short story about a robot discovering emotions.”
  • Data Analysis:
    Prompt: “What are the key steps to clean a dataset before analysis?”

Remember, the AI’s response quality often depends on how precisely you craft your prompt. Don’t be afraid to experiment and iterate.

A Quick Note on Froala Integration

Because DeepSeek is an API-based service, it can be embedded into various applications—including our very own Froala WYSIWYG Editor. While I won’t dive too deep here, imagine the possibilities: AI-assisted content suggestions, grammar checks, or auto-generated text snippets, all triggered within the Froala editing environment. That’s the kind of seamless experience we’re looking to unlock for our users. An example is how you can build note-taking apps with DeepSeek API.

Final Thoughts

Getting up and running with DeepSeek API is straightforward:

  1. Secure your API key.
  2. Set up your environment.
  3. Experiment with prompts to discover what the AI can do.

Beyond these basics, the real magic happens when you start chaining requests together—enabling more robust applications like smart chatbots, recommendation engines, or creative content generators. The potential is vast, and if you ever decide you want to integrate these features into Froala, the door is wide open.

Have fun coding, and don’t be shy about pushing the boundaries. Whether you’re a seasoned developer or just curious about the AI landscape, DeepSeek is a powerful tool that can help bring your most creative ideas to life. If you run into any snags, check out the official documentation or tap into the community for support.

Integrating Froala HTML Editor Software in Angular 19 With SSR Enabled

HTML Editor Software

Froala has recently upgraded its Angular SDK to support Angular 19. With this update, developers can now integrate the Froala WYSIWYG Editor into their Angular 19 applications with server-side rendering (SSR) enabled. This allows for improved performance, better SEO, and enhanced user experience.

The updated SDK provides a seamless integration process, making it easier for developers to incorporate the feature-rich Froala Editor into their Angular projects. This integration enables users to create and edit content within the Angular application, while benefiting from the advantages of server-side rendering.

In this article, we will explore the step-by-step process of integrating the Froala WYSIWYG Editor into an Angular 19 application with server-side rendering enabled. We will cover the necessary setup, configuration, and implementation details to ensure a seamless integration. By the end of this guide, you will have a comprehensive understanding of how to leverage the power of Froala within your Angular 19 project.

Getting Started with Your Angular App

First, make sure you have the Angular CLI installed. The CLI is a powerful command-line tool that lets you create, develop, and manage Angular projects right from your terminal.

Don’t have the CLI installed yet? No problem, just run this command:

npm install -g @angular/cli

Now you’re ready to start building your Angular app. Let’s create a new project called “froala-app” by running:

ng new froala-app

You’ll be asked a couple of questions along the way:

  1. Which stylesheet format would you like to use? Choose your preferred CSS preprocessor, like SCSS or Sass.
  2. Do you want to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)? This is an important one! Enabling SSR and SSG will make your Angular app more performant and SEO-friendly. Go ahead and type “Y” to turn it on.

Once you’ve answered these questions, an Angular project structure will be created in a new folder called “froala-app”. Navigate into the project directory using

cd froala-app

Install the Froala Angular SDK

Alright, let’s get the Froala Angular rich-text editor installed into your Angular application. The Froala Angular SDK has all the essential tools and components you need to easily integrate the Froala editor functionality into your Angular app.

Just run this command to get it installed:

npm install angular-froala-wysiwyg

Create a Standalone Component for Handling The Editor

Now, let’s create another component that we can use to integrate the Froala editor. We’ll call it the “my-editor” component.

ng generate component myEditor

This will create a new folder called “my-editor” inside the “src/app” directory. Inside you’ll find these files for the “my-editor” component:

  • my-editor.component.css
  • my-editor.component.html
  • my-editor.component.spec.ts
  • my-editor.component.ts

Import Froala Components

Open up the my-editor.component.ts file and let’s import the necessary Froala SDK components:

import { Component } from '@angular/core';

import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';




@Component({

  selector: 'app-my-editor',

  standalone: true,

  imports: [FroalaEditorModule, FroalaViewModule],

  templateUrl: './my-editor.component.html',

  styleUrl: './my-editor.component.css'

})

export class MyEditorComponent {}

Insert Froala Editor HTML Code

Now let’s add the Froala editor HTML code to the my-editor.component.html file:

<div [froalaEditor]>Hello, Froala!</div>

 

Styling the Froala Editor

To make sure the Froala editor looks good, we need to include the necessary stylesheets. In the angular.json file, add these Froala stylesheets under the “styles” array:

            "styles": [

              "src/styles.css",

              "node_modules/froala-editor/css/froala_editor.pkgd.min.css",

              "node_modules/froala-editor/css/froala_style.min.css"

            ],

The froala_editor.pkgd.min.css includes the styles for the core editor and all Froala plugins. The froala_style.min.css includes the styles needed for displaying the content created by the editor outside the editor.

Displaying Froala on the main page

Finally, let’s import the MyEditorComponent into the app.component.ts file so we can use it in the main app template:

import { Component } from '@angular/core';

import { CommonModule } from '@angular/common';

import { RouterOutlet } from '@angular/router';

import { MyEditorComponent } from './my-editor/my-editor.component';




@Component({

  selector: 'app-root',

  standalone: true,

  imports: [CommonModule, RouterOutlet, MyEditorComponent],

  templateUrl: './app.component.html',

  styleUrl: './app.component.css'

})

export class AppComponent {

  title = 'froala-app';

}

And in the app.component.html file, replace the main section with:

<main class="main">

  <div class="content">

    <app-my-editor></app-my-editor>

  </div>

</main>

Start your App

Alright, now you can serve the app by running ng serve. This will compile the application and serve it locally, usually at http://localhost:4200/. You can now open your Angular app in a web browser and you should see the Froala editor displayed on the homepage.

Froala in Angular 19

Displaying More Froala’s Features

You may have noticed that the Froala editor is displayed with just its basic features. That’s because we haven’t included the plugin’s JavaScript files in the ngOnInit() method yet. Let’s take care of that now.

Open up the “my-editor.component.ts” file and let’s start adding some Froala plugins one by one:

import { isPlatformBrowser } from '@angular/common';

import { Component, Inject, PLATFORM_ID } from '@angular/core';

import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';




@Component({

  selector: 'app-my-editor',

  standalone: true,

  imports: [FroalaEditorModule, FroalaViewModule],

  templateUrl: './my-editor.component.html',

  styleUrl: './my-editor.component.css'

})

export class MyEditorComponent {

  constructor(@Inject(PLATFORM_ID) private platformId: Object) { }




  ngOnInit() {

    // Import Froala plugins dynamically only in the browser context

    if (isPlatformBrowser(this.platformId)) {




      // Import a single Froala Editor plugin.

      // @ts-ignore

      import('froala-editor/js/plugins/align.min.js');




      // Import a Froala Editor language file.

      // @ts-ignore

      import('froala-editor/js/languages/de.js');




      // Import a third-party plugin.

      // @ts-ignore

      import('froala-editor/js/third_party/font_awesome.min');

      // @ts-ignore

      import('froala-editor/js/third_party/image_tui.min');

      // @ts-ignore

      import('froala-editor/js/third_party/spell_checker.min';

      // @ts-ignore

      import('froala-editor/js/third_party/embedly.min');

    }

  }

}

Alternatively, if you want to load all the Froala features with a single call, you can import the plugins.pkgd.js file instead:

import { isPlatformBrowser } from '@angular/common';
import { Component, Inject, PLATFORM_ID } from '@angular/core';
import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';

@Component({
  selector: 'app-my-editor',
  standalone: true,
  imports: [FroalaEditorModule, FroalaViewModule],
  templateUrl: './my-editor.component.html',
  styleUrl: './my-editor.component.css'
})
export class MyEditorComponent {
  constructor(@Inject(PLATFORM_ID) private platformId: Object) { }

  ngOnInit() {
    // Import Froala plugins dynamically only in the browser context
    if (isPlatformBrowser(this.platformId)) {
      // Import all Froala Editor plugins.
      // @ts-ignore
      import('froala-editor/js/plugins.pkgd.min.js');

    }
  }
}

In the code above, we’re using the isPlatformBrowser component to make sure we only import the Froala plugins in the browser context. This is important for server-side rendering (SSR) scenarios.

The // @ts-ignore is used to suppress any TypeScript errors that might come up due to the dynamic import statements. This allows the code to compile without issues, and the plugins will be loaded at runtime.

How to Setup Froala if Server-side Rendering is disabled

If you’ve disabled server-side rendering (SSR) in your Angular application, the way you import the Froala SDK components may be a bit different. Instead of importing SDK components in my-editor.component.ts, we’ll update the my-editor.module.ts file as follows:

// Import all Froala Editor plugins.
// import 'froala-editor/js/plugins.pkgd.min.js';

// Import a single Froala Editor plugin.
// import 'froala-editor/js/plugins/align.min.js';

// Import a Froala Editor language file.
// import 'froala-editor/js/languages/de.js';

// Import a third-party plugin.
// import 'froala-editor/js/third_party/font_awesome.min';
// import 'froala-editor/js/third_party/image_tui.min';
// import 'froala-editor/js/third_party/spell_checker.min';
// import 'froala-editor/js/third_party/embedly.min';

// Import Angular plugin.
import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';
...

@NgModule({
   ...
   imports: [FroalaEditorModule.forRoot(), FroalaViewModule.forRoot() ... ],
   ...
})

Customizing The Editor

Now that we’ve set up the Froala editor in our Angular application, it’s time to start customizing it to fit our needs. We can enable additional features and plugins, adjust the toolbar buttons, and even create custom functionality.

The Froala SDK provides a wide range of options to tailor the editor to our specific requirements. By leveraging the power of Angular and the flexibility of Froala, we can build a robust and feature-rich text editing experience for our users.

Let’s open the my-editor.component.ts file and define a public options object in the MyEditorComponent class with some customizations from the Froala API options, events, and methods:

export class MyEditorComponent {

  public options: Object = {

    toolbarButtons: ['alignRight', 'bold', 'insertImage'],

    events: {

      'froalaEditor.contentChanged': function () {

        console.log('Content updated!');

      },

    },

  };

  .....

And in the my-editor.component.html file, we’ll assign the options object to the Froala component:

<div [froalaEditor]="options">Hello, Froala!</div>

Is it possible to store uploaded files in the cloud with Froala?

Absolutely! Froala offers two convenient ways for uploading files:

  1. Built-in File Upload: Froala’s built-in file upload functionality seamlessly integrates with your Angular application, and you can configure it to upload files directly to your S3 bucket.
  2. Filestack Integration: Froala also integrates with Filestack, a powerful upload and cloud storage solution. This integration gives you advanced file handling capabilities, allowing you to securely store and manage your application’s files. The Filestack integration streamlines the file upload experience within your Angular-powered app and offers easy integration with various cloud storage services.

The Filestack integration requires minimal configuration – you’ll need to create a Filestack account to get an API key.

Both options make it easy to incorporate file upload functionality into your Angular application, enhancing the content creation experience for your users.

Conclusion

In this article, we’ve explored the seamless integration of the Froala HTML Editor software into an Angular 19 application with server-side rendering (SSR) enabled. By leveraging the updated Froala Angular SDK, we were able to quickly set up the editor.

The step-by-step guide covered the necessary setup, configuration, and implementation details to ensure a smooth integration process. We also discussed how to customize the Froala editor to fit the specific needs of your Angular application including enabling additional features and plugins.

Moreover, we highlighted the two convenient options for storing uploaded files in the cloud – the built-in file upload functionality and the Filestack integration. Both of these solutions make it easy to incorporate secure and scalable file management into your Angular-powered application.

By following the instructions in this article, you now have the knowledge and tools to integrate the powerful Froala WYSIWYG Editor into your Angular 19 project, while taking advantage of the benefits of server-side rendering. Start enhancing your users’ content creation experience today!

Try Froala in your Angular 19 application and see the difference it can make. Get started with the Froala Angular SDK now.

 

Integrating Froala as a Functional Component in React 18

Froala as a functional component

As a React developer, you’re always on the lookout for the latest tools and technologies to enhance your development workflow. In this blog post, we’ll explore how you can seamlessly integrate a powerful rich text editor, Froala Editor, into your React 18 applications.

Froala 4.4 and React 18 Support

Froala, a leading provider of content editing solutions, has recently released version 4.4 which now fully supports React 18. This means that you can easily incorporate the Froala Editor v4.4 into your React 18 projects, taking advantage of the latest features and improvements in the React ecosystem.

Benefits of Updating to Froala 4.4

By updating your application to use the Froala React SDK, you’ll be able to:

  • Leverage the latest features and enhancements in the Froala Editor
  • Ensure compatibility with the latest version of React (18)
  • Improve the overall performance and user experience of your application.

Integrating Froala as a Functional Component

To get started with integrating Froala as a functional component in your React 18 application, follow these steps:

  1. Install the Froala 4.4 React SDK:
npm install react-froala-wysiwyg --save
  1. Create a functional component that uses the Froala Editor. Create a new directory in the src directory called components and create a file called MyEditorComponent.jsx in that directory.
  2. Open MyEditorComponent.jsx and import the Froala Editor component and the necessary CSS files.
import React from "react";

// Require Editor CSS files.

import "froala-editor/css/froala_style.min.css";

import "froala-editor/css/froala_editor.pkgd.min.css";

import FroalaEditorComponent from "react-froala-wysiwyg";

// Import all Froala Editor plugins;

// import 'froala-editor/js/plugins.pkgd.min.js';

// Import a single Froala Editor plugin.

// import 'froala-editor/js/plugins/align.min.js';

// Import a language file.

// import 'froala-editor/js/languages/de.js';

// Import a third-party plugin.

// import 'froala-editor/js/third_party/image_tui.min.js';

// import 'froala-editor/js/third_party/embedly.min.js';

// import 'froala-editor/js/third_party/spell_checker.min.js';

// Include font-awesome css if required.

// install using "npm install font-awesome --save"

// import 'font-awesome/css/font-awesome.css';

// import 'froala-editor/js/third_party/font_awesome.min.js';
  1. Render the Froala SDK component
// Render Froala Editor component.

function MyEditorComponent() {

  return (

    <div class="editor">

      <h3> Froala's React WYSIWYG Editor</h3>

      <FroalaEditorComponent tag="textarea" />

    </div>

  );

}

export default MyEditorComponent;
  1. Add to other components. For example, to add in `src/App.js`
import "./styles.css";

import MyEditorComponent from "./components/MyEditorComponent";

export default function App() {

  return (

    <div className="App">

      <h1>Hello CodeSandbox</h1>

      <h2>Start editing to see some magic happen!</h2>

      <MyEditorComponent />

    </div>

  );

}

By following these steps, you can easily integrate the Froala Editor as a functional component in your React 18 application, allowing your users to create and edit rich content with ease.

Froala Editor Customization In React

To further customize the Froala Editor in your React 18 application, you can leverage the various configuration options and event handlers provided by the Froala API.

Add a config attribute to the FroalaEditorComponent utilizing the Froala options, events, and methods to customize the editor to your needs.

function MyEditorComponent() {

  let config = {

    documentReady: true,

    heightMin: 300,

    events: {

      contentChanged: function (e, editor) {

        console.log("test");

      },

    },

  };

  return (

    <div class="editor">

      <h3> Froala's React WYSIWYG Editor</h3>

      <FroalaEditorComponent tag="textarea" config={config} />

    </div>

  );

}

This allows you to tailor the editor’s appearance, functionality, and behavior to match the specific needs of your project.

Additionally, you can integrate third-party plugins and language files to extend the editor’s capabilities, ensuring a seamless and feature-rich content editing experience for your users.

By taking advantage of these customization options, you can create a truly unique and engaging rich text editing solution within your React 18 application.

Why Should I Use Froala With React in 2025?

Using Froala with React in 2025 offers several key advantages. Firstly, the tight integration between the Froala Editor and the React ecosystem ensures seamless compatibility with the latest React features and best practices. This allows you to leverage the full power of React 18 and beyond, delivering a highly responsive and performant content editing experience.

Additionally, Froala’s robust plugin ecosystem and extensive customization options enable you to tailor the editor to your specific requirements, ensuring a unique and engaging user interface for your application.

Froala Editor V4 integrates with Filestack to provide a seamless cloud storage solution for images, videos, and other file types.

By embracing Froala and React in 2025, you can future-proof your content management solutions and provide your users with a cutting-edge rich text editing experience.

How Easy Is It To Upload Images In Froala with React?

Froala makes it easy to upload images in your React application. They offer two convenient options:

  1. Built-in Image Upload: Froala’s built-in image upload functionality seamlessly integrates with your React app. All you need to do is configure the Froala Editor’s image upload options, and your users can upload images directly from their devices or external sources. The only additional step is setting up a server to store the uploaded images.
  2. Filestack Integration: Froala also integrates with Filestack, a powerful upload and cloud storage solution. This integration gives you advanced file handling capabilities, allowing you to securely store and manage your application’s media assets. The Filestack integration streamlines the image upload experience within your React-powered app. Plus, you can apply image transformations directly within the Froala Editor, before or after uploading the images.

The Filestack integration requires minimal configuration – you’ll just need to create a Filestack account to get an API key.

Both options make it easy to incorporate rich image functionality into your React application, enhancing the content creation experience for your users.

Why is Froala significantly cheaper than TinyMCE?

Froala’s transparent pricing model provides a fixed annual fee for using the editor and all its features. Unlike TinyMCE, Froala does not impose limits on the number of editor loads or charge extra for additional features. Consequently, Froala is significantly cheaper than TinyMCE in many use cases.

This cost-effectiveness, combined with Froala’s robust customization capabilities and seamless integration with React, makes it an attractive choice for developers seeking a high-quality WYSIWYG editor for their React 18 applications.

How to Migrate from TinyMCE to Froala in React?

Migrating from TinyMCE to Froala in a React application is a straightforward process. The key steps involve removing the TinyMCE SDK, installing the Froala SDK, importing the necessary components, and configuring the editor to match your existing setup.

By following this comprehensive migration from TinyMCE to Froala in React guide, you can seamlessly transition your content editing experience, preserving your users’ familiarity while benefiting from Froala’s features, customization options, and cost-effective pricing model.

Conclusion

Integrating the Froala Editor as a functional component in your React 18 application is a powerful way to enhance your content creation and management capabilities. By leveraging the latest version of Froala and taking advantage of its seamless compatibility with React 18, you can deliver a cutting-edge rich text editing experience to your users.

The step-by-step guide provided in this article walks you through the process of setting up the Froala Editor as a reusable component, allowing you to easily customize it to match the unique needs of your project. With Froala’s robust plugin ecosystem, extensive configuration options, and tight integration with cloud storage solutions like Filestack, you can create a truly unique and engaging content editing workflow within your React 18 application.

If you’re a React developer looking to elevate your content management capabilities, we encourage you to try integrating Froala Editor into your next project. Froala is an excellent choice that will help you deliver a superior user experience for your application’s content creators.

If you have any questions or need further assistance, don’t hesitate to reach out to the Froala team or explore the comprehensive documentation.

How to add Froala HTML Editor Software in Django in 2025

add HTML editor software in Django

Django is a powerful Python web framework that helps developers build web applications quickly and efficiently. Froala 4.4 release adds support to the popular Python framework, Django 5.

Integrating Froala HTML Editor Software into a Django project allows users to create and edit rich text content within the application. By combining the flexibility of Froala and the rapid development capabilities of Django, you can create dynamic, user-friendly web applications that meet the evolving needs of your audience.

In this step-by-step guide, you’ll learn how to integrate the Froala HTML Editor Software into a Django form, allowing your users to create and edit rich text content within your application. Whether you’re building a blog, a content management system, or any other web application, this integration will enhance the user experience and unlock new possibilities for your project.

Integrate Froala into Django

Prerequisites

Being a Python web framework, Django requires Python. We’re assuming:

  • You are familiar with Python and have it installed on your computer. If not, please install python and come again.
  • You have Django installed already.

Versions Used in This Tutorial

  • Froala Editor V4.4
  • Python V3.13.1
  • Django V5.1.5

Step 1: Getting started

From the command line, cd into a directory where you’d like to store your code and create a new directory named froaladjangotutorial.

mkdir froaladjangotutorial
 Then, run the following command to bootstrap a new Django project:
django-admin startproject myapp froaladjangotutorial

This will create a project called myapp inside the froaladjangotutorial directory.

Step 2: Creating a Demo app

To create your app, jump into the created directory:

cd froaladjangotutorial

Type the following command:

py manage.py startapp demos

That’ll create a directory demos which will contain our demo code.

Step 3: Install Froala

To begin, you’ll need to install the Froala Django package. You can do this using pip.

pip install django-froala-editor

Install Froala Django SDK

After successfully installed, open myapp/settings.py and add froala_editor into the INSTALLED_APPS array.

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'froala_editor'
]

Then open the myapp/urls.py file and include the Froala Editor URLs.

from django.contrib import admin
from django.urls import include,path

urlpatterns = [
    path("demos/", include("demos.urls")),
    # Froala Editor URLs
    path('froala_editor/', include('froala_editor.urls')),
    path('admin/', admin.site.urls),
]

Step 4: Create a form with a Froala

Create a new file demos/forms.py and add the following code:

from django import forms
from froala_editor.widgets import FroalaEditor

class FroalaForm(forms.Form):
    content = forms.CharField(widget=FroalaEditor)
 In the above code, we've created a Django form with a FroalaEditor widget. 

Step 5: Configure Froala

You can also customize the editor’s appearance and behavior by passing various options to the FroalaEditor widget.

For example, to initialize the Froala Editor with an inline toolbar, you can use the following code:

from django import forms
from froala_editor.widgets import FroalaEditor

class FroalaForm(forms.Form):
    content = forms.CharField(widget=FroalaEditor(options={
      'toolbarInline': True,
    }))

This will create a Froala Editor instance with an inline toolbar, allowing users to format the content as needed. You can further customize the editor by modifying the options passed to the FroalaEditor widget.

Step 6: Create a template to render the form

You’ll need to configure the Froala Editor in your Django templates. In the demos app, create a new file called froala_form.html in the /templates directory. In this file, you’ll add the necessary HTML and Django template tags to integrate the Froala Editor.

 

<!DOCTYPE html>
<html>

<head>
    <title>Froala Editor</title>
    {{ form.media }}


</head>

<body>
    <h1>Froala Editor</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</button>
    </form>

</body>

</html>

Make sure to update your settings.py to include the templates directory in the TEMPLATES setting:

import os

# ...existing code...

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'demos', 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
 

Step 7: Update the view to render the template

Update your demos/views.py file to render the form in the template:

from django.shortcuts import render
from .forms import FroalaForm

def index(request):
    if request.method == 'POST':
        form = FroalaForm(request.POST)
        if form.is_valid():
            # Process the form data
            pass
    else:
        form = FroalaForm()
    
    return render(request, 'froala_form.html', {'form': form})

Step 8: Map The URLs

Define a URLconf for the demos app by creating a file demos/urls.py with the following content:

from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
]

The next step is to configure the global URLconf in the myapp project to include the URLconf defined in demos.urls.

To do this, add an import for django.urls.include in myapp/urls.py and insert an include() in the urlpatterns list, so you have:

from django.contrib import admin
from django.urls import include,path

urlpatterns = [
    path("demos/", include("demos.urls")),
    path('admin/', admin.site.urls),
]

Step 9: Test the demo app

Verify the demo app is working with the following command:

python manage.py runserver

You can now access the demo app by visiting `http://127.0.0.1:8000/demos/` in your web browser. This will display the form you created, including the Froala Editor.

Froala into Django

With the Froala Editor integrated into your Django application, users can now create and edit rich text.

Conclusion

Integrating the Froala WYSIWYG Editor into your Django application is a powerful way to enable rich text editing for your users. By following the steps outlined in this article, you can quickly add a feature-rich text editor to your Django forms.

The Froala Editor provides a wide range of customization options, allowing you to tailor the editor to your specific needs. Whether you want an inline toolbar, custom buttons, or advanced formatting options, the Froala Editor has you covered.

Now that you know how to add the Froala Editor to your Django project, why not give it a try? Start by creating a new Django project and follow the steps in this guide. Before long, you’ll have a dynamic, user-friendly text editing experience integrated into your web application.

A Step-by-Step Guide To Export Froala WYSIWYG Editor To PDF

PDF export

As a tech-savvy user or entry-level developer, you’re always on the lookout for tools that can streamline your workflow and enhance your productivity. Today, we’re excited to introduce you to the Froala WYSIWYG Editor and its powerful PDF export feature.

Froala is a feature-rich, user-friendly text editor that allows you to create and format content with ease. Whether you’re writing blog posts, drafting technical documentation, or designing marketing materials, Froala’s intuitive interface and robust functionality make it a valuable asset in your content creation arsenal.

In this blog post, we’ll dive deep into the PDF export feature of the Froala WYSIWYG Editor, guiding you step-by-step on how to set it up and leverage it to your advantage.

Key Takeaways:

  1. The Froala WYSIWYG Editor provides a powerful PDF export feature that allows you to easily convert your content into professional-looking PDF documents.
  2. The PDF export feature relies on the “html2pdf.js” library, which must be included in your project for the feature to work.
  3. You can customize the PDF export by configuring options like page size, orientation, and margins using the “html2pdf” option provided by the Froala Editor.
  4. Strategically using CSS page break properties can help you control where the page breaks occur in the exported PDF document.

Downloading and Setting Up Froala WYSIWYG Editor

To get started, you’ll need to download the Froala WYSIWYG Editor. You can visit the pricing page and choose the plan that best suits your needs. Whether you’re a solo developer or part of a larger team, Froala offers a range of licensing options to accommodate your requirements. If you want to test the editor first, you can also take advantage of the free trial option.

Once you’ve downloaded and installed the Froala WYSIWYG Editor, it’s time to set it up. The process is straightforward and can be completed in a few simple steps:

  1. Include the necessary CSS and JavaScript files in your HTML document.
  2. Initialize the Froala Editor by adding the appropriate HTML element and JavaScript code.
  3. Customize the editor’s appearance and functionality by configuring the available options.

Here’s an example of how you can set up the Froala WYSIWYG Editor:

<!DOCTYPE html>
<html>

<head>
    <title>Froala WYSIWYG Editor</title>
    <!-- Include Froala CSS -->
    <link href="{{editor__download__folder}}/css/froala_editor.pkgd.min.css" rel="stylesheet"
        type="text/css" />
</head>

<body>
    <!-- HTML element where the editor will be initialized -->
    <div id="editor">
        <p>This is the initial content of the editor.</p>
    </div>


    <!-- Include Froala Editor JS files -->
    <script type="text/javascript" src="{{editor__download__folder}}/js/froala_editor.pkgd.min.js"></script>

    <script>
        // Initialize the Froala Editor
        new FroalaEditor('#editor');
    </script>
</body>

</html>

This example demonstrates the basic setup for the Froala WYSIWYG Editor. You can further customize the editor by adding additional configurations to suit your specific needs.

Exploring the PDF Export Feature

Now that you have the Froala WYSIWYG Editor set up, let’s dive into the PDF export feature. This powerful functionality allows you to seamlessly convert your content into a professional-looking PDF document, making it easy to share, print, or archive your work.

Since we are using the packaged version of Froala “froala_editor.pkgd.min.js“, this feature is included by default.

If you’re using the basic version of Froala (froala_editor.min.js), you’ll need to include the Froala PDF export plugin in your project.

<script type="text/javascript" src="{{editor__download__folder}}/js/froala_editor.min.js"></script>
<script type="text/javascript" src="{{editor__download__folder}}/js/plugins/print.min.js"></script>

Make sure to include the “print” plugin in the list of enabled plugins:

new FroalaEditor('#editor', { 
       pluginsEnabled: ['print'],
});
 With the plugin in place, you can now add the PDF export button to your Froala Editor toolbar. Here's an example of how to do that:
new FroalaEditor('#editor', { 
       pluginsEnabled: ['print'],
       toolbarButtons: ['getPDF'],
});

This configuration will add an “Export PDF” button to your Froala Editor toolbar. However, users will still be unable to export the content as PDF documents. That’s because the PDF export feature depends on the html2pdf.jsopen-source library. You’ll need to include this library in your project as well. The “html2pdf.js” script must be included before the Froala scripts.

    <!-- Include js2htm library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.min.js"
        integrity="sha512-YcsIPGdhPK4P/uRW6/sruonlYj+Q7UHWeKfTAkBW+g83NKM+jMJFJ4iAPfSnVp7BKD4dKMHmVSvICUbE/V1sSw=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <!-- Include Froala Editor JS files -->
    <script type="text/javascript" src="{{editor__download__folder}}/js/froala_editor.min.js"></script>
    <script type="text/javascript" src="{{editor__download__folder}}/js/plugins/print.min.js"></script>

Note that, as mentioned on html2pdf.js site, there have been some issues reported with the latest version of html2pdf.js (v0.10), so it’s recommended to use version 0.9.3 for now.

Exporting Content as PDF

Now that you have the PDF export feature set up, let’s walk through the process of exporting your content as a PDF document.

  1. Add Content to the Froala Editor: Start by adding your desired content to the Froala WYSIWYG Editor. This could be a blog post, a technical guide, or any other type of content you want to export as a PDF.
  2. Click the PDF Export Button: Once you’ve finished editing your content, locate the “PDF Export” button in the Froala Editor toolbar and click it.

That’s it! You’ve successfully exported your Froala WYSIWYG Editor content as a PDF document. This feature is particularly useful when you need to share your work with others, print it, or archive it for future reference.

Export Editor Content to PDF Programmatically

The Froala Editor’s Print plugin provides a toPDF() method that allows you to export the editor’s content to a PDF document programmatically. This can be useful when you want to trigger the PDF export after a specific event, such as when the editor initializes.

Here’s an example of how to export the content to PDF right after the editor is initialized:

        // Initialize the Froala Editor
        new FroalaEditor('#editor', {
            pluginsEnabled: ['print'],
            toolbarButtons: ['getPDF'],
        }, function () {
            this.print.toPDF();


        });

The toPDF() method uses the default Froala PDF export options.

Customizing the PDF Export

If you want to customize the exported PDF, such as setting the orientation to portrait instead of landscape, you can use the html2pdf option provided by the Froala Editor.

The html2pdf option returns a function that gives you access to the html2pdf.js Worker object. With this object, you can trigger any html2pdf methods. Read more about how to use it in the html2pdf documentation.

You can use this object to configure the PDF settings and then export the editor’s content following this format editor.opts.html2pdf().set(configration).from(editor.el).save();.

Here’s an example:

        // Initialize the Froala Editor
        new FroalaEditor('#editor', {
            pluginsEnabled: ['print'],
            toolbarButtons: ['getPDF'],
        }, function () {

            let editor = this;

            editor.opts.html2pdf().set({
                margin: [10, 20],
                html2canvas: { useCORS: !0 },
                filename: 'new name.pdf',
                jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
            }).from(editor.el).save();
        });

In this example, we’re setting the following PDF options:

  • margin: Specifies the PDF margins in points.
  • html2canvas.useCORS: Enables CORS (Cross-Origin Resource Sharing) for the HTML2Canvas library, which is used to capture the editor’s content.
  • filename: Sets the name of the exported PDF file.
  • jsPDF: Configures the PDF document settings, such as the unit, page format, and orientation.

After setting the options, we use the from(editor.el) method to specify the editor element as the content to be converted to PDF, and then call the save() method to generate and download the PDF file.

Remember, setting the configuration incorrectly could result in an empty or incorrectly formatted PDF file, so be cautious when customizing the PDF export.

Adding Page Breaks

The html2pdf.js library automatically adds page breaks based on your CSS styles. You can use the break-before, break-after, and break-inside CSS properties to control where the page breaks should occur.

For example, you can add a page break before a specific element by applying the break-before: always style to it. This ensures that the element starts on a new page when you export the content to PDF.

Additionally, you can add the html2pdf__page-break class to any element, and html2pdf.js will insert a page break after that element. This is a legacy feature, but it can still be useful in some cases.

To summarize, make sure to add the appropriate CSS page break styles to your content. When you export the Froala Editor’s content to PDF, html2pdf.js will automatically insert the page breaks based on your CSS rules, resulting in a well-formatted PDF document.

Conclusion

In this blog post, we’ve explored the powerful PDF export feature of the Froala WYSIWYG Editor. By following the step-by-step guide, you now know how to download and set up the Froala Editor, as well as how to leverage the PDF export functionality to streamline your content creation and sharing workflows.

Whether you’re a tech-savvy user or an entry-level developer, the Froala WYSIWYG Editor and its PDF export feature can be a valuable asset in your content creation toolkit. By mastering these tools, your users will be able to create professional-looking documents, enhance your productivity, and deliver high-quality content to their audience.

So, what are you waiting for? Download Froala, try out the PDF export feature, and start creating amazing content today!

HTML Code Writer with Iframe Isolation and How to Inject Styles

HTML Iframe

Looking to seamlessly integrate a rich text editor into your web application without disrupting your existing design or compromising security? Leveraging the power of iframes, the Froala WYSIWYG editor offers a robust solution for achieving just that. This approach provides a clean, isolated environment for the editor, preventing style conflicts and potential security vulnerabilities.

This article delves into the advantages of loading your Froala editor within an iframe, exploring the benefits of content isolation and enhanced customization options. We’ll provide a clear, step-by-step guide on how to effectively embed the Froala editor in an iframe, and discuss techniques for injecting custom styles to maintain brand consistency and a polished user experience.

Key Takeaways:

  1. Using an iframe to embed the Froala WYSIWYG editor provides content isolation, preventing style conflicts between the editor and the main website. This ensures a consistent editing experience regardless of the surrounding website’s CSS.
  2. Froala’s iframe mode allows developers to inject custom styles directly into the iframe, enabling precise control over the editor’s visual presentation to maintain brand consistency.
  3. Embedding the Froala editor in an iframe is a straightforward process.

HTML Code Writer

The Benefits of Using HTML Iframe with Froala Editor

Understanding the Advantages of Iframe Content Isolation

Iframes offer a powerful way to embed external content seamlessly within your web pages while maintaining a clean separation from your core site’s structure and styling. Think of them as miniature windows displaying content from other sources.

With the Froala WYSIWYG editor, utilizing iframe mode provides significant advantages, primarily centered around content isolation. This iframe editor customization ensures that the styling of your Froala editor, embedded within the iframe, won’t clash with the CSS of your main webpage. This is particularly crucial when dealing with complex website designs or when integrating third-party content. This isolation prevents conflicts and ensures a consistent editing experience within the Froala editor, regardless of the surrounding website’s styles.

Furthermore, iframe content isolation enhances security by limiting the impact of potentially malicious scripts within the embedded content, protecting your website’s integrity. Using iframes with the Froala editor allows for a more controlled and predictable integration, contributing to a smoother user experience and simplified development process.

The Froala editor embedding process is straightforward and designed to enhance both UX and DX, aligning perfectly with Froala’s mission to create exceptional editing experiences.

Enhancing Your WYSIWYG Editor with Iframe Customization

The ability to set default styles for framed WYSIWYG editors’ content is particularly beneficial for maintaining brand consistency and ensuring seamless visual integration.

How do you achieve this level of iframe editor customization? It’s simpler than you might think. Injecting styles into the framed Froala editor allows you to precisely tailor the look and feel to match your brand’s guidelines. This precise control extends to fonts, colors, button styles, and virtually every aspect of the editor’s visual presentation.

With Froala’s focus on intuitive design and developer experience, customizing your framed editor becomes a powerful tool for creating a visually appealing and user-friendly editing experience within your web application.

How to Embed Froala Editor in an Iframe Effectively

The Froala WYSIWYG editor, known for its clean design and developer-friendly integration, provides a dedicated iframe mode, further enhancing its versatility and customization capabilities.

First, include the Froala library in your project. Then, when initializing the editor, set the iframe option to true. This creates a contained environment for the editor, preventing style conflicts with the surrounding webpage.

new FroalaEditor('div#froala-editor', {
  iframe: true
})

This isolation is especially beneficial when dealing with complex website designs, ensuring the Froala editor renders perfectly regardless of existing CSS. This method offers several advantages, including iframe content isolation and enhanced iframe editor customization.

How To Inject Styles Inside Froala WYSIWYG Editor

Enabling Froala’s iframe mode brings us to the matter of styling the framed editor. Because of the inherent content isolation, simply adding CSS to your main stylesheet won’t affect the editor within the iframe. This is where the Froala core.injectStyle(style) method comes into play.

This method is used to inject styles directly into the iframe’s document. This approach allows precise control over the editor’s visual presentation within its contained environment, overcoming the limitations posed by iframe SEO impact and ensuring consistent styling regardless of the parent page’s CSS.

For example, by default, the standard browser’s font-size for the H1 tag is 32px. This is the font size that will be automatically applied to H1 elements inside the Froala editor when used in iframe mode. However, you may want to change this default to match your brand’s style guide – for instance, setting the H1 font-size to 40px. In this case, you can use core.injectStyle(style) method like this:

let editor = new FroalaEditor(
  "div#froala-editor",
  {
    iframe: true,
  },
  function () {
    // Call the method inside the initialized event.
    editor.core.injectStyle("h1{font-size: 40px}")
  },
)

The code above sets the font-size for any H1 tags inserted within the Froala editor to 40px, ensuring the editor’s appearance matches your brand’s design guidelines.

With this technique, developers can achieve seamless iframe editor customization while leveraging the benefits of iframe content isolation and enhanced security. This allows for a streamlined user experience that makes Froala a favorite among developers worldwide.

FAQ

1. What are the benefits of using HTML iframe for embedding the Froala Editor?

Using an iframe for the Froala Editor offers several key benefits: content isolation (preventing style conflicts with your main website and enhancing security), enhanced customization (allowing precise control over the editor’s appearance through style injection), and a cleaner separation of content which can potentially improve page load times and thus, SEO. It creates a contained environment, simplifying development and ensuring a consistent editing experience.

2. How can I customize the Froala Editor when loaded in an iframe?

Customize the framed Froala editor by injecting styles directly into the iframe’s document using the core.injectStyle(style) method. This allows precise control over fonts, colors, button styles, and more, ensuring brand consistency.

Conclusion

Embedding the Froala editor within an iframe offers a compelling blend of design flexibility, enhanced security, and improved site stability. While iframe implementation requires careful consideration of SEO implications, the benefits of content isolation and styling customization often outweigh the challenges. By understanding the nuances of iframe integration and leveraging Froala’s intuitive design, developers can create a seamless and visually appealing editing experience that enhances user satisfaction and development workflow. So, take the leap and explore the power of iframe embedding with Froala – you might be surprised at how easily it elevates your web application’s editing capabilities.

Froala’s Best Innovative Approach to Styling JavaScript WYSIWYG Editor Tables

Styling JavaScript WYSIWYG Editor Tables

Tables are best used in JavaScript WYSIWYG Editors. They help us organize data, highlight important information, and present content in a clear, structured way. However, styling these tables has long been a frustrating challenge for non-technical users.

Froala came up with an innovative approach to table styling, giving developers the ability to create ready visually stunning styles that content creators can select to style their tables.

In this post, we’ll explore Froala’s table styling capabilities. We’ll uncover why Froala’s table solution seamlessly fits into any content.

Styling JavaScript WYSIWYG Editor Tables

Key Takeaways:

  • Froala provides a comprehensive set of table formatting options in its rich-text editor, including the ability to resize columns, add/remove table headers/footers, and control cell alignment.
  • Froala’s innovative table styling capabilities allow developers to create pre-designed table styles that content creators can easily apply to their tables, without needing to write custom CSS.
  • Froala’s table styling features improve the readability and aesthetics of content by enabling the creation of professional-looking tables that enhance the overall visual appeal.
  • Froala’s seamless table editing tools streamline the content creation process, boosting productivity by reducing the time spent on table formatting.
  • By integrating Froala’s powerful yet user-friendly table management capabilities, you can elevate the quality and impact of your content, delivering a better experience for your audience.

Table Editing in Froala

When it comes to styling tables in a rich-text editor, Froala provides a comprehensive set of formatting options to help you create professional-looking tables.

Table Structure

Froala’s rich text editor provides a powerful “Table” dropdown menu that gives you complete control over the structure of your tables. This menu allows you to easily manipulate your table, ensuring you can create the perfect layout for your content.

With the “Table” dropdown, you can:

Add/Remove Table Header: Toggle a header row at the top of your table. This is great for labeling the different columns and providing context for your data.

Add/Remove Table Footer: Add a footer row at the bottom of your table. This can be useful for including summary information, totals, or other important details.

Add/Remove Table Rows: Quickly insert new rows or delete existing ones as needed. This flexibility allows you to expand your table to accommodate more data or trim it down to only the most essential information.

Add/Remove Table Columns: Just like with rows, you can add or remove columns at any time. This makes it easy to reorganize your content and adjust the table structure to suit your needs.

Beyond just adding and removing elements, the “Table” dropdown also lets you control the alignment of content within each cell. You can choose to align text horizontally (left, center, right, justify) as well as vertically (top, middle, bottom). This allows you to present your data in a visually appealing and organized manner.

Moreover, Froala provides the ability to merge and split cells, giving you complete control over the table structure. This flexibility ensures that you can create complex table layouts to best suit your content.

Styling Tables with Froala

One of the biggest challenges with rich-text editors is styling tables. Most WYSIWYG editors don’t provide an easy solution for non-technical users to style their tables.

But Froala has an intuitive approach to table styling. Let’s say you want to create a striped table style. You can add the following CSS rule to your stylesheet:

.class1 tbody tr:nth-child(2n) {

  background: #f9f9f9;

}

This rule will apply a light gray background color to every other row in the table, creating a striped effect.

Next, you can define this new table style in the tableStyles option of the Froala Editor:

new FroalaEditor('div#froala-editor', { 
      // Define new table cell styles 
       tableStyles: {
         class1: 'Stripped',
       }
});

In this example, the key class1 represents the CSS class that will be applied to the table, and the value 'Striped' is the label that will be displayed in the “Table Style” dropdown menu for users to select.

When a user selects the “Striped” option from the dropdown, the class1 CSS class will be applied to the table, resulting in the striped appearance you defined earlier.

This approach allows you, as the developer, to create a range of pre-designed table styles that users can easily apply to their content. By providing these visually appealing options, you empower your users to create professional-looking tables without having to write any custom CSS themselves.

Additionally, you can control whether users can select multiple table styles at once or if they should be limited to a single style. This is done using the tableMultipleStyles option in the Froala Editor configuration.

With Froala’s robust table styling capabilities, content creators can focus on creating high-quality, visually appealing content, without getting bogged down by the complexities of table formatting.

Styling Table Cells with Froala

In addition to styling entire tables, Froala also allows you to apply custom styles to individual table cells. This granular control enables you to highlight specific data, draw attention to important information, or create visually distinct sections within your tables.

To style table cells, Froala provides a “Cell Style” dropdown menu that lets users select from a range of predefined styles. Similarly to “Table Style”, as the developer, you can define these styles using CSS and then expose them in the editor’s interface. This empowers your users to easily apply professional-looking formatting to their content without any coding knowledge.

Let’s say you want to allow users to style some cell text in red so they are highlighted. You can add the following CSS rule to your stylesheet:

.redcell {
   text-align: center;
   color: red;
}

Next, set the tableCellStyles option of the Froala Editor:

new FroalaEditor('div#froala-editor', {
   // Define new table cell styles.
   tableCellStyles: {
     redcell: 'highlight',
   }
})

When a user selects the “highlight” option from the dropdown, the redcell CSS class will be applied to the table cell, resulting in the selected cell text appearing in red.

table cell style

This flexibility allows users to emphasize important data, create visual hierarchies, and ensure their tables are informative and aesthetically pleasing.

With these powerful table styling capabilities, content creators can craft professional-looking tables that effectively communicate their message and enhance the overall visual appeal of their content.

Benefits of Froala’s Table Styling

Improved Readability and Aesthetics

Froala’s table styling capabilities help create clean, professional-looking tables that enhance the overall appearance and readability of your content. With a range of formatting options, you can ensure a consistent look and feel across your entire document.

This attention to detail results in an enhanced user experience, making it easier for your audience to navigate and digest the information presented in your tables. Well-styled tables can significantly improve the clarity and impact of data-heavy content, whether it’s in a corporate blog, online documentation, or e-commerce product descriptions.

Increased Productivity

Froala’s intuitive table editing tools streamline the content creation process, allowing you to spend less time fussing with table formatting and more time focusing on the substance of your work. The seamless integration of tables with other rich-text elements, such as text, images, and multimedia, further enhances your productivity by enabling a smooth, efficient workflow.

By reducing the development time required for custom table implementations, Froala’s table styling capabilities free up your team to concentrate on higher-value tasks and deliver content to your audience more quickly.

Conclusion

Froala’s innovative approach to table styling in javaScript WYSIWYG editors has solved a long-standing challenge for content creators. By providing an intuitive set of table formatting options and the ability to define custom table styles, Froala empowers users to create professional-looking tables without requiring any specialized technical knowledge.

To experience the benefits of Froala’s table styling firsthand, we encourage you to explore the Froala Editor and integrate it into your next project. With its powerful yet user-friendly table management capabilities, you can elevate the quality and impact of your content, delivering a better experience for your audience.

Enhancing a Lightweight WYSIWYG Editor with a File Uploader: A Developer’s Guide

Creating user-friendly and efficient tools is essential. WYSIWYG (What You See Is What You Get) editors help users create and format content without needing to know HTML or CSS. Lightweight WYSIWYG editors are especially popular because they load quickly and are easy to integrate into projects. However, to make these editors even more powerful, adding a file uploader is a great idea. This guide will show you how to add a file uploader to a lightweight WYSIWYG editor using Froala and Filestack as examples.

What is a Lightweight WYSIWYG Editor?

A WYSIWYG editor allows users to see how their content will look while they are creating it. A lightweight editor means it has a small file size, loads quickly, and doesn’t use a lot of computer resources. These editors are perfect for projects where speed and efficiency are important.

Why Choose Lightweight Editors?

  • Faster Performance: They load quickly, making your website or application run smoother.
  • Easy to Integrate: Simple to add to your project without complicated setup.
  • Customizable: Easy to adjust to fit your specific needs.
  • Better User Experience: Provides a smooth and responsive interface for creating content.

Why Add a File Uploader?

Adding a file uploader to your WYSIWYG editor makes it easier for users to include images, videos, documents, and other media in their content. This not only makes the content more engaging but also improves the overall user experience.

Benefits of File Uploaders:

  • Richer Content: Users can add various types of media to their content.
  • User-Friendly: Features like drag-and-drop and multiple file uploads make it easy to use.
  • Developer Efficiency: Offloads the task of handling files to specialized services, saving time and effort.

Tools You’ll Need

Froala Editor

Froala is a modern, lightweight WYSIWYG editor known for its speed and flexibility. It offers many features while keeping its file size small, making it a great choice for developers.

Filestack

Filestack is a powerful service that helps you upload, transform, and deliver files easily. It supports many file types and offers features like resizing, cropping, and optimizing files. Filestack also ensures your files are delivered quickly and reliably through its global network.

Step-by-Step Tutorial: Integrating Filestack with Froala

Follow these simple steps to add a file uploader to your Froala editor using Filestack.

1. Set Up Your Development Environment

First, you need to include the necessary CSS and JavaScript files for both Froala and Filestack in your HTML file.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Froala & Filestack Integration</title>
  <!-- Load Froala Editor CSS files -->
  <link href='https://cdn.jsdelivr.net/npm/[email protected]/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />
  
  <!-- Load Filestack Transformation UI CSS files -->
  <link rel="stylesheet" href="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css" />
</head>
<body>
  <div id="editor">Type something...</div>

  <!-- Load Filestack JS -->
  <script src="https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js"></script>       
  <script src="https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js"></script>
  
  <!-- Load Filestack Transformation UI JS -->
  <script src="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js"></script>
  
  <!-- Load Froala Editor JS files -->
  <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/[email protected]/js/froala_editor.pkgd.min.js'></script>
  
  <!-- Initialize Froala Editor with Filestack Integration -->
  <script>
    const filestackClient = filestack.init('YOUR_FILESTACK_API_KEY'); // Replace with your Filestack API key

    // Initialize the Froala Editor
    new FroalaEditor('#editor', {
      imageEditButtons: ['imageReplace', 'imageAlign', 'imageCaption', 'filestackIcon', 'imageTUI'],

      filestackOptions: {
        uploadToFilestackOnly: false,
        filestackAPI: 'YOUR_FILESTACK_API_KEY', // Replace with your Filestack API key
        pickerOptions: {
          fromSources: [
            'local_file_system',
            'imagesearch',
            'url',
            'googledrive',
            'facebook',
          ],
          accept: [
            ".pdf",
            "image/jpeg",
            "image/png",
            "image/webp",
            "video/*",
            "audio/*"
          ],
          transformations: {
            "crop": true,
            "rotate": true
          }
        },
      },
    });
  </script>
</body>
</html>

2. Initialize the Froala Editor

The HTML above sets up the Froala editor inside a div with the ID editor. The Froala Editor is initialized with options that allow it to work with Filestack for file uploads.

3. Configure Filestack Integration

In the JavaScript section, you need to initialize Filestack with your API key and configure Froala to use Filestack for handling file uploads.

const filestackClient = filestack.init('YOUR_FILESTACK_API_KEY'); // Replace with your Filestack API key

// Initialize the Froala Editor
new FroalaEditor('#editor', {
  imageEditButtons: ['imageReplace', 'imageAlign', 'imageCaption', 'filestackIcon', 'imageTUI'],

  filestackOptions: {
    uploadToFilestackOnly: false,
    filestackAPI: 'YOUR_FILESTACK_API_KEY', // Replace with your Filestack API key
    pickerOptions: {
      fromSources: [
        'local_file_system',
        'imagesearch',
        'url',
        'googledrive',
        'facebook',
      ],
      accept: [
        ".pdf",
        "image/jpeg",
        "image/png",
        "image/webp",
        "video/*",
        "audio/*"
      ],
      transformations: {
        "crop": true,
        "rotate": true
      }
    },
  },
});

Key Options Explained:

  • imageEditButtons: Adds Filestack-specific buttons to the image editing toolbar in Froala.
  • filestackOptions:
    • uploadToFilestackOnly: If set to true, only Filestack handles uploads. If false, other sources can also upload files.
    • filestackAPI: Your Filestack API key for authenticating upload requests.
    • pickerOptions:
      • fromSources: Lists the sources users can upload files from, like their local system or Google Drive.
      • accept: Specifies the types of files users can upload, such as PDFs and images.
      • transformations: Enables options like cropping and rotating images directly in the uploader.

4. Exploring Advanced Integration Modes

Froala offers different ways to integrate with Filestack, allowing you to choose how much control you want over the upload process.

Demo #1: Basic Mode

In Basic Mode, Filestack’s file picker and transformation tools are added to Froala’s existing upload options. This mode enhances Froala without changing its default upload behavior.

new FroalaEditor('#editor', {
  imageEditButtons: ['imageReplace', 'imageAlign', 'imageCaption', 'filestackIcon', 'imageTUI'],

  filestackOptions: {
    uploadToFilestackOnly: false,
    filestackAPI: 'YOUR_FILESTACK_API_KEY',
    pickerOptions: {
      fromSources: [
        'local_file_system',
        'imagesearch',
        'url',
        'googledrive',
        'facebook',
      ],
      accept: [
        ".pdf",
        "image/jpeg",
        "image/png",
        "image/webp",
        "video/*",
        "audio/*"
      ],
      transformations: {
        "crop": true,
        "rotate": true
      }
    },
  },
});

Demo #2: Advanced (Filestack-only) Mode

Advanced Mode uses Filestack exclusively for all file uploads in Froala. This gives you complete control over the upload process through Filestack.

new FroalaEditor('#editor', {

  filestackOptions: {
    uploadToFilestackOnly: true,
    filestackAPI: "YOUR_FILESTACK_API_KEY"
  },

  events: {
    'filestack.uploadedToFilestack': function (response) {
      console.log("File uploaded to Filestack:", response);
    },

    'filestack.filestackPickerOpened': function () {
      console.log("Filestack picker opened");
    },

    'filestack.filestackPickerClosed': function () {
      console.log("Filestack picker closed");
    },

    'filestack.uploadFailedToFilestack': function (error) {
      console.log("File upload failed:", error);
    },
  },

});

Key Points in Advanced Mode:

  • uploadToFilestackOnly: Set to true to ensure all uploads go through Filestack.
  • events: Customize how your application responds to different stages of the upload process, like when a file is uploaded or if an upload fails.

Demo #3: Enable Transformation UI after Image Uploads

Filestack’s Transformation UI allows users to edit images right after uploading. They can adjust brightness, contrast, size, and apply filters. To enable this feature, adjust the transformationsUI option.

 

new FroalaEditor('#editor', {
  filestackOptions: {
    uploadToFilestackOnly: true,
    filestackAPI: "YOUR_FILESTACK_API_KEY",
    pickerOptions: {
      transformationsUI: true,
    } 
  },
});

 

Benefits of Transformation UI:

  • Real-Time Editing: Users can edit images immediately after uploading.
  • Professional Enhancements: Apply filters and effects easily.
  • User-Friendly Interface: Simple controls make it easy for users to customize images.

5. Best Practices for Integration

To make sure your integration works smoothly and securely, follow these best practices:

Security Considerations:

  • File Validation: Check files on both the client side and server side to ensure only allowed types and sizes are uploaded.
  • Secure Connections: Use HTTPS to protect data during upload.
  • Access Control: Make sure only authorized users can upload and access files.

Performance Optimization:

  • Optimize Images: Compress and resize images before uploading to save bandwidth and improve load times.
  • Lazy Loading: Load images only when needed to speed up page loads.
  • Efficient Caching: Use Filestack’s CDN to deliver files quickly to users around the world.

User Experience Enhancements:

  • Progress Indicators: Show upload progress bars to keep users informed.
  • Error Handling: Provide clear messages if something goes wrong during upload.
  • Intuitive Interface: Make the upload process simple with features like drag-and-drop.

6. Testing and Debugging

Thorough testing ensures your integration works well for all users. Here’s how to test and fix common issues:

Testing Upload Functionality:

  • Different File Types: Try uploading various files like images, videos, and documents to ensure compatibility.
  • Multiple Files: Check that the editor can handle multiple uploads at once.
  • Edge Cases: Test with large files, slow internet connections, and unsupported file types to see how your system handles them.

Debugging Common Issues:

  • Network Errors: Make sure your application can handle network problems gracefully and allow users to retry uploads.
  • API Key Errors: Verify that your Filestack API key is correct and has the right permissions.
  • Compatibility Issues: Ensure the integration works on different browsers and devices, and fix any issues that arise.

Conclusion

Adding a file uploader to a lightweight WYSIWYG editor like Froala can greatly enhance its functionality. By integrating Filestack, you enable users to easily upload and manage files, making content creation more efficient and engaging. This guide provided a simple, step-by-step approach to setting up this integration, ensuring that your editor remains fast and user-friendly.

Next Steps:

  • Explore More Features: Look into additional options and settings in Froala and Filestack to further customize your editor.
  • Optimize for Your Needs: Adjust the integration to fit the specific requirements of your project, whether it’s a blog, a content management system, or a single-page application.
  • Stay Updated: Keep up with updates from Froala and Filestack to take advantage of new features and improvements.

By following these steps and best practices, you can create a robust and user-friendly content editing tool that meets the needs of modern web applications.

Elevate Your Froala File Uploads: Harnessing Filestack’s Robust Event System

enhance file uploading experience

Filestack doesn’t just offer a reliable file uploading solution – it empowers you to craft a truly exceptional user experience. By harnessing Filestack’s robust event system, you can take control of every step of the file upload process and delight your users like never before.

The Filestack events allow developers to handle different scenarios, such as when a file is selected, when the upload is in progress, or when the upload is completed.

By leveraging these events, developers can create a more seamless and user-friendly file uploading experience for your users. This can include providing feedback on the upload status, handling errors, and integrating the uploaded files into the application’s workflow. This is the power of Filestack’s events that you can leverage to enhance the file uploading experience within the Froala editor.

In a previous article, we explored the foundational events like onOpen, onFileSelected, and onCancel. Now, let’s dive deeper and uncover how the onFileUploadCancel, onFileUploadFailed, onFileUploadFinished, and other Filestack events can help you elevate your file uploading experience to new heights.

Events for enhancing file uploading experience

Key Takeaways

  • Filestack’s robust event system allows developers to handle different scenarios in the file upload process, such as file selection, upload progress, upload completion, and errors.
  • By leveraging events like onFileUploadCancel, onFileUploadFailed, onFileUploadFinished, and others, developers can create a more seamless, transparent, and user-friendly file management workflow within their Froala-powered applications.
  • Implementing these Filestack events allows developers to provide visual feedback, handle errors gracefully, and integrate the uploaded files into their application’s functionality, resulting in a more polished and delightful experience for users.
  • Integrating Filestack into Froala-based applications unlocks the full potential of file management, allowing developers to enhance their users’ trust and confidence in their application’s file handling capabilities.

Improving the File Upload Cancellation Experience

The onFileUploadCancel event lets you handle when a user cancels a file upload. By listening to this event, you can:

  • Provide visual feedback to the user
  • Update the application’s state
  • Ensure a smooth experience even when a file upload is interrupted

This event gives you control to gracefully handle cancellations and maintain the coherence of your application’s file management workflow.

The onFileUploadCancel event receives an object containing the cancelled file’s metadata. You can use this information to update your UI and application state accordingly.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onFileUploadCancel: (file) => {
                console.log(file.size);
            }
        }
    }
});

By handling the onFileUploadCancel event, you can create a more responsive and transparent file uploading experience for your users.

Improving the File Upload Start Experience

The onUploadStarted and onFileUploadStarted events let you know when a file upload has begun. By handling these events, you can keep users informed about the status of their uploads, which builds trust and confidence in your application’s file management capabilities.

The onUploadStarted event fires when the user clicks the upload button. It provides an array of file metadata objects. The onFileUploadStarted event fires when a file begins uploading. It provides the metadata for the file being uploaded.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
           onUploadStarted: (files) => {
              console.log(files[0].size);
            },
           onFileUploadStarted: (file) => {
            console.log(file.size);
          },
        }
    }
});

Improving the File Upload Progress Experience

The onFileUploadProgress event allows you to track the multi-part upload progress of local files. This enables you to provide users with a visual representation of the upload status, such as progress bars or spinners. By leveraging this event, you can create a more responsive and transparent file uploading experience, building trust and confidence in your application.

The onFileUploadProgress event fires repeatedly during the file upload process. It provides the file metadata and an FSProgressEvent object containing information about the upload progress.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onFileUploadProgress: (file, ProgressEvent) => {
                console.log(file.size);
                console.log(ProgressEvent);
            }
        }
    }
});

By handling the onFileUploadProgress event, you can create a more engaging and informative file uploading experience for your users.

Improving the File Upload Failed Experience

The onFileUploadFailed event lets you handle failed file uploads. This allows you to provide users with meaningful feedback and guidance. When this event fires, you can:

  • Display error messages to inform users about the issue
  • Suggest troubleshooting steps to help users resolve the problem
  • Automatically retry the upload to recover from the failure

By handling the onFileUploadFailed event, you can significantly improve the overall user experience. This makes your application more resilient and user-friendly. It ensures users are never left in the dark when encountering upload issues, fostering trust and confidence in your application’s file management capabilities.

The onFileUploadFailed event provides the file metadata and an error object. You can use this information to give users the necessary feedback and guidance.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onFileUploadFailed: (file, error) => {
                console.log(file.size);
                console.log(error);
            }
        }
    }
});

By handling the onFileUploadFailed event, you can create a more robust and user-friendly file uploading experience.

Improving the Successful Uploads Experience

The onFileUploadFinished event lets you handle successful file uploads. When this event fires, you can:

  • Update your application’s state to reflect the new file
  • Integrate the uploaded file into your workflow
  • Provide visual feedback to the user, such as a success message

This event allows you to seamlessly incorporate the uploaded files into your application. This creates a cohesive and efficient file management experience for your users. By handling onFileUploadFinished, you can ensure your application responds effectively to successful file uploads, enhancing the overall user experience.

The onFileUploadFinished event provides the uploaded file’s metadata, which you can use to update your application accordingly.

Explain
new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onFileUploadFinished: (file) => {
                console.log(file.size);
            }
        }
    }
});

You can create a more polished and user-friendly file uploading experience by leveraging the event.

Improving the Upload End Experience

The onUploadDone event allows you to handle the completion of a file upload, whether successful or not. This event gives you the opportunity to perform cleanup, update your application’s state, or trigger additional actions based on the upload outcome. By using this event, you can ensure a seamless and comprehensive file management experience, allowing users to confidently interact with your application’s file handling.

The onUploadDone event receives an object containing two arrays: filesFailed and filesUploaded. The filesFailed array contains metadata for failed uploads, while the filesUploaded array contains metadata for successful uploads. You can use this information to take appropriate actions, such as displaying error messages for failed uploads or integrating the successful uploads into your application.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
          onUploadDone: (files) => {
             console.log(files.filesUploaded[0].size);
          },
        }
    }
});

How Filestack Integration in Froala Editor Works?

The Filestack integration in Froala Editor provides a straightforward way to enable powerful file management and upload capabilities. This integration was introduced in Froala V4.3, making it easy for developers to leverage Filestack’s features.

To get started, you’ll need a free Filestack API key. Once you have that, you can follow the steps outlined in the Filestack integration guide for Froala. This guide will walk you through the necessary setup and configuration to integrate Filestack within your Froala-powered application.

With the Filestack plugin, Froala developers can unlock a wide range of file management features, including:

  • Seamless file uploads
  • Robust file processing capabilities
  • Advanced file transformation options
  • Secure file storage and delivery

By integrating Filestack, Froala developers can enhance the file handling experience for their users, creating a more polished and feature-rich application.

Conclusion

In this article, we demonstrate how Filestack’s robust event system can help Froala developers elevate the file uploading experience for their users. By leveraging events like onFileUploadCancel, onFileUploadFailed, onFileUploadFinished, and others, you can create a more seamless, transparent, and user-friendly file management workflow within your Froala-powered applications.

Implementing these Filestack events allows you to provide visual feedback, handle errors gracefully, and integrate the uploaded files into your application’s functionality. This results in a more polished and delightful experience for your users, building their trust and confidence in your application’s file handling capabilities.

If you’re a Froala developer looking to enhance your file uploading experience, we encourage you to explore the power of Filestack’s events. Integrate Filestack into your Froala-based applications and unlock the full potential of file management for your users. Get started with Filestack today and take your Froala-powered experiences to new heights!

Customizing Filestack File Picker: the New Froala File Uploading Option – Part 2

file uploading

Imagine a JavaScript tool – where it can effortlessly handle upload, store, and process your files with a few lines of code. That’s the power of Filestack, a file management tool that has processed over 1 billion files and counting.

Filestack now has official integration with Froala, offering many customization options that allow developers to create a truly seamless and intuitive file uploading process within the Froala editor tailored for your users.

We explored some of the Filestack File Picker customization options available to developers before. In this second part of the series, we will explore additional customization options related to events, uncovering how you can customize the file uploading experience from start to finish – from the moment the user opens the picker to handle the successful (or failed) upload.

Let’s delve into these customization features that help you create a smooth and intuitive file management workflow within your Froala-powered applications, significantly improving user experience.

Key Takeaways:

  1. Filestack provides a range of customization options and events that allow developers to create a highly responsive and tailored file picker experience within Froala-powered applications.
  2. The onOpen event can be used to enhance the user experience when the File Picker UI mounts, such as displaying a custom loading indicator or updating the UI.
  3. The onFileSelected event enables developers to validate selected files, reject files that don’t meet certain criteria, and even modify the file name if needed.
  4. The onFileCropped event provides metadata about the cropped image, allowing developers to perform additional processing before inserting it into the Froala editor.
  5. The onCancel event can be used to customize the user experience when file uploads are cancelled, ensuring the application remains responsive and user-friendly.
  6. The onClose event triggers when the File Picker UI is exited, providing an opportunity to perform any necessary cleanup or additional actions.

Enhance File Uploading experience

Customize the File Picker Opening Experience

Filestack’s onOpen event triggers when the File Picker UI mounts. You can use this event to enhance the user experience. For example, you can display a custom loading indicator or update the UI to provide feedback.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onOpen: filepicker => {
                console.log(filepicker);
            }
        }
    }
});

The onOpen callback receives the PickerInstance interface, which provides the following methods:

  • cancel() Cancels any ongoing uploads. This operation is idempotent and returns a Promise.
    new FroalaEditor("div#froala-editor", {
        filestackOptions: {
            filestackAPI: 'yourAPIKey',
            pickerOptions: {
                onOpen: PickerInstance => {
                    //Cancel picker uploads. 
                    PickerInstance.cancel();
                }
            }
        }
    });
    
  • close() Closes the File Picker. This operation is idempotent and returns a Promise.
    new FroalaEditor("div#froala-editor", {
        filestackOptions: {
            filestackAPI: 'yourAPIKey',
            pickerOptions: {
                onOpen: PickerInstance => {
                    //Close the File Picker.
                    PickerInstance.close();
                }
            }
        }
    });
    
  • open() Opens the File Picker. This operation is idempotent.
  • crop(urls) Specifies a list of file URLs to open in the Picker for cropping.
    new FroalaEditor("div#froala-editor", {
    filestackOptions: {
            filestackAPI: 'yourAPIKey',
            pickerOptions: {
                onOpen: PickerInstance => {
                    const urls = [
                        'https://d1wtqaffaaj63z.cloudfront.net/images/fox_in_forest1.jpg',
                        'https://d1wtqaffaaj63z.cloudfront.net/images/sail.jpg',
                    ];
                    PickerInstance.crop(urls);
                }
            }
        }
    });
    

Leverage the onOpen event and the PickerInstance methods to create a more engaging user experience.

Handling User Selected Files

The onFileSelected event in Filestack triggers whenever a user selects a file. You can use this event to validate the selected file and, if necessary, reject the selection by throwing an error. The error message will be displayed to the user as an alert.

For example, you can reject files that exceed a certain size limit:

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onFileSelected: file => {
                if (file.size > 1000 * 1000) {
                    throw new Error('File too big, select something smaller than 1MB');
                }
            }
        }
    }
});

Developers can use this event to change the selected file name if it’s uploaded from the local source.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onFileSelected: file => {
                // It's important to return a new file by the end of this function.
                return { ...file, name: 'foo' };
            }
        }
    }
});

The onFileSelected event also supports asynchronous validation logic. You can return a Promise from the callback function and then resolve or reject the Promise as needed:

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onFileSelected: file => {
                return new Promise((resolve, reject) => {
                    // Do something async
                    resolve();
                    // Or reject the selection with reject()
                  });
            }
        }
    }
});

By leveraging the onFileSelected event, you can create a more robust and user-friendly file selection experience within your Froala-powered applications.

Handling Cropped Files

When a user uploads an image using the File Picker, Filestack displays a simple image editor. This editor allows the user to crop, circle crop, and rotate the image.

Filestack triggers the onFileCropped event when the user crops the image. This event provides an object with the file metadata, such as the file size. You can use this metadata to perform additional processing on the cropped image before inserting it into the Froala editor.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onFileCropped : (file) => {
                console.log(file.size);
            }
        }
    }
});

The onFileCropped event provides the necessary information to handle the cropped image, allowing you to integrate the cropping functionality seamlessly into your application’s workflow.

Customize User Experience When Files Get Cancelled

Filestack triggers the onCancel event when all uploads in the File Picker are cancelled. This event receives an object containing the file’s metadata.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onCancel: PickerUploadDoneCallback => {
                console.log(PickerUploadDoneCallback);
            }
        }
    }
});

Handling the onCancel event gives you the flexibility to customize the user experience when the file upload is interrupted, ensuring your application remains responsive and user-friendly. By providing feedback and handling the cancellation scenario, you can create a more engaging and intuitive file management workflow within your Froala-powered applications. This helps to enhance the overall user experience and ensure your users feel in control of the file upload process, even when they choose to cancel it.

Customize the File Picker Closing Experience

Filestack triggers the onClose event when the File Picker UI is exited.

new FroalaEditor("div#froala-editor", {
    filestackOptions: {
        filestackAPI: 'yourAPIKey',
        pickerOptions: {
            onClose: () => {
                console.log('File Picker closed');
            }
        }
    }
});

Looking For Other Events?

Beyond the events mentioned, Filestack provides a range of other events such as onFileUploadCancel, onFileUploadFailed, onFileUploadFinished, onFileUploadProgress, onFileUploadStarted, onUploadDone, and onUploadStarted that you can leverage to customize the file uploading experience. Refer to the Filestack documentation for a comprehensive list of available options and their usage.

Conclusion

Filestack File Picker is a powerful tool for handling file uploads. Users appreciate its ease of use, support for various upload sources, dependability, and straightforward cloud storage integration. Filestack offers many customization options and events that allow developers to create a highly responsive and tailored file picker experience.

From validating file selections to handling cropped images and managing the overall file upload workflow, these events empower you to customize the user experience to your specific needs. Explore the full range of Filestack events and integrate them seamlessly into your application’s logic. This ensures a smooth and intuitive file management process for your users.

If you’re looking to enhance the file-uploading experience in your Froala-powered applications, try the Filestack integration today. Its robust set of customization features will help you create a seamless and user-friendly file management workflow.

 

Get your Filestack API here for free.

Customizing Filestack File Picker: the New Froala File Uploading Option – Part 1

customization

Froala, a popular rich text editor, just got even better with its latest update. Froala V4.3+ now supports the Filestack File Picker as a new option for uploading images, videos, and files.

The Filestack File Picker offers a user-friendly interface that improves the uploading file experience. By integrating Filestack, Froala users can now leverage its robust file management capabilities to simplify the entire upload process, delivering a much smoother experience for their users.

One of the advantages of Filestack File Picker is its many customization options, such as restricting file types and setting upload size limits. In this article, we’ll dive into some of the customization options available to Froala users when integrating the Filestack File Picker.

By leveraging these powerful features, you can create a truly seamless and intuitive file management workflow within your Froala-powered applications, taking the user experience to new heights.

How Can I Customize The File Picker Within the Froala Editor?

To start using Filestack File Picker for file uploading within the Froala editor, you have to include its scripts and stylesheet files within your project and configure the filestackOptions.filestackAPI option with a valid API key which you can get from Filestack DevPortal for free.

Here’s an example of what your HTML code might look like:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" name="viewport" content="width=device-width, height=device-height, initial-scale=1.0,
            maximum-scale=1.0" />
        <link href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel="stylesheet"
            type="text/css" />
              <link rel="stylesheet" href="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css" />

    </head>
    <body>
        <div id="froala-editor"> </div>
        <script type="text/javascript"
            src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js"></script>
         <script src="https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js"></script>
  <script src="https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js"></script>
  <script src="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js"></script>
        
        <script>
                new FroalaEditor("div#froala-editor",{
                  filestackOptions{
                    filestackAPI: 'yourAPIKey',
                  }
                });
        </script>
        </body>
</html>

To customize the File Picker, you can add your custom configuration to the filestackOptions.pickerOptions option. In this case, the Froala initialization code would be similar to:

  new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        transformationsUI: true
      }
    }
  });

Customization Options

Restrict File Types

You can restrict the file types that users can upload by setting the accept option within the  filestackOptions.pickerOptions configuration. For example, to only allow image files, you can use accept: 'image/*'. You can also specify multiple file types by providing an array, such as accept: ['image/*', 'video/*', 'application/pdf']. This ensures that users can only upload the file types that are relevant to your application, enhancing the overall user experience. The formats that you can assign through this option are:

  • .pdf <- accept PDF files.
  • image/jpeg <- any MIME type commonly known by browsers
  • image/* <- accept all types of images
  • video/* <- accept all types of video files
  • audio/* <- accept all types of audio files
  • application/* <- accept all types of application files
  • text/* <- accept all types of text files
  new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        accept: ['image/*', 'video/*']
      }
    }
  });

If you need to restrict other file types, you can use the acceptFn option which allows you to provide a custom function to determine which files are accepted. This gives you full control over the file type validation process.

The acceptFn has two parameters:

  • PickerFileMetadata
  • PickerAcceptFnOptions

And you have to return the Promise<string> .

  new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        acceptFn: (file, options) => {
           return options.mimeFromMagicBytes(file.originalFile).then((res) => { // we can check mimetype from magic bytes
             //console.log(options.mimeFromExtension(file.originalFile.name)); // or check extension from filestack extensions database
             // throw new Error('Cannot accept that file') // we can throw exception to block file upload
             // return Promise.reject('Cannot accept that file'') // or reject a promise
             return Promise.resolve();
           });
        }
      }
    }
  });

By leveraging the acceptFn, Froala users can ensure that only the appropriate files are uploaded, maintaining the integrity and consistency of the content within their Froala-powered applications. This level of customization empowers them to tailor the file upload experience to their specific needs, enhancing the overall user experience.

Restrict File Size

You can also set upload size limits using the maxSize option within the filestackOptions.pickerOptions configuration. This allows you to restrict the maximum file size that users can upload, helping to manage storage and bandwidth constraints. For example, to set a 10MB limit, you can use maxSize: 10 * 1024 * 1024. This ensures that users cannot upload files that exceed your specified size limit, improving the overall file management process.

  new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        maxSize: 10 * 1024 * 1024
      }
    }
  });

By setting appropriate size limits, you can ensure that the file upload process aligns with your application’s requirements and provides a seamless user experience.

Restrict Allowed Image Dimensions

You can also set accepted image dimensions using the imageDim option within the filestackOptions.pickerOptions configuration. This allows you to specify the exact width and height for uploaded JPEG, PNG, and BMP images, ensuring that they meet your application’s requirements.

Local and cropped images will be resized (upscaled or downscaled) to the specified dimensions before uploading. The original height to width ratio is maintained. To resize all images based on the width, set [width, null], e.g. [800, null]. For the height set [null, height], e.g. [null, 600].

  new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        imageDim: [800, 600]
      }
    }
  });

This helps maintain visual consistency and quality within your Froala-powered content.

Instead, if you prefer to give your users some freedom, you can use imageMax and imageMin options where imageMax allows you to set the maximum allowed dimensions. Images bigger than the specified dimensions will be resized to the maximum size while maintaining the original aspect ratio.

imageMin allows you to set the minimum allowed image dimensions. Images smaller than the specified size will be upscaled to the minimum size while maintaining the original aspect ratio.

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        imageMax: [1800, 1600],
        imageMin: [800, 600],

      }
    }
  });

This gives users more flexibility while still ensuring the images meet your application’s requirements. By leveraging these options, you can strike a balance between maintaining visual consistency and providing users with a more open file upload experience.

Restrict Upload Number

You can also restrict the number of files that users can upload at once by setting the maxFiles option within the filestackOptions.pickerOptions configuration. This helps you manage the upload process and ensure that users don’t overwhelm your application with too many files at once. For example, to limit the number of files to 5, you can use maxFiles: 5.

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         maxFiles: 5,
         
      }
    }
  });

Additionally, you can set the minimum number of files that users must upload at once by setting the minFiles option within the filestackOptions.pickerOptions configuration. This can be useful if your application requires a certain number of files to be uploaded together, such as multiple images for a product listing. For example, to require at least 3 files to be uploaded, you can use minFiles: 3.

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         maxFiles: 5,
         minFiles: 3
      }
    }
  });

By setting both maxFiles and minFiles, you can strike a balance between providing flexibility and maintaining control over the file upload process, ensuring that your Froala-powered application meets your specific requirements.

By default, the upload process didn’t start until the user hit the “Upload“ button. If you want to start uploading automatically when maxFiles is hit, set the startUploadingWhenMaxFilesReached option to true.

Restrict Concurrency Upload Number

You can also restrict the number of concurrent file uploads by customizing the concurrency option within the filestackOptions.pickerOptions configuration, which is by default set to 4. This allows you to control the maximum number of files that can be uploaded simultaneously, preventing your application from being overwhelmed and ensuring a smooth upload experience. By setting an appropriate value for concurrency, you can balance the need for efficient file uploads with the available resources and bandwidth of your application.

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         concurrency: 2,
      }
    }
  });

 

Restrict Video Resolution

You can also restrict the video resolution of uploaded files using the videoResolution option within the filestackOptions.pickerOptions configuration. This allows you to specify the maximum width and height for video files to one of these values “320×240”, “640×480” or “1280×720”, ensuring that they meet your application’s requirements. By default, it is "640x480". By setting appropriate limits, you can optimize storage, bandwidth, and playback performance, while maintaining the desired visual quality for your Froala-powered content.

 

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         videoResolution: "1280x720",
      }
    }
  });

 

Customize Upload Sources

You can also specify the upload sources that users can choose from by setting the fromSources option within the filestackOptions.pickerOptions configuration. This allows you to restrict the file selection to specific sources, such as local device storage, cloud storage providers, or social media platforms. For example, to only allow users to upload files from their local device and Google Drive, you can use fromSources: ['local_file_system', 'google_drive']. This helps streamline the file upload process and ensures that users can only access the file sources that are relevant to your application. Valid ones are:

  • local_file_system – Default
  • url – Default
  • imagesearch – Default
  • facebook – Default
  • instagram – Default
  • googledrive – Default
  • dropbox – Default
  • webcam – Uses device menu on mobile. Not currently supported in Safari and IE.
  • video – Uses device menu on mobile. Not currently supported in Safari and IE.
  • audio – Uses device menu on mobile. Not currently supported in Safari and IE.
  • box
  • github
  • gmail
  • googlephotos
  • onedrive
  • onedriveforbusiness
  • customsource – Configure this in your Filestack Dev Portal.
  • unsplash

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         fromSources: ['local_file_system', 'google_drive'],
      }
    }
  });

Cleaning JPEG Image EXIF

You can also configure Filestack to automatically remove EXIF data from JPEG images during the upload process. This can be useful for reducing the file size and ensuring that sensitive metadata, such as location information, is not inadvertently included in the uploaded images. To enable this feature, you can set the cleanupImageExif option within the filestackOptions.pickerOptions configuration to true.

 

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         cleanupImageExif: true,
      }
    }
  });

 

This option also offers the ability to keep image orientation by assigning it to an object and setting a keepOrientation property to true. Moreover, you can keep image color profiles by setting keepICCandAPP property to true.

 new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
         cleanupImageExif: {
           keepOrientation: true,
           keepICCandAPP: false
         },
      }
    }
  });

By doing so, you can streamline the file upload process and maintain better control over the data being stored in your Froala-powered application.

Enable Transformation UI

You can also enable the Transformation UI to allow users to perform advanced image editing, including filters and overlay text, alongside basic operations like cropping and rotating, directly in the file picker. To enable this feature, you can set the transformationsUI option within the filestackOptions.pickerOptions configuration to true.

This provides users with a more robust file editing experience, allowing them to customize their uploads before they are sent to your application.

  new FroalaEditor("div#froala-editor",{
    filestackOptions{
      filestackAPI: 'yourAPIKey',
      pickerOptions: {
        transformationsUI: true
      }
    }
  });

Conclusion

In this article, we’ve explored the powerful customization options available when integrating the Filestack File Picker into your Froala-powered applications. By leveraging features like file type restrictions, upload size limits, image dimension controls, and more, you can create a truly seamless and intuitive file management workflow for your users.

These customization capabilities empower Froala users to tailor the file upload experience to their specific needs, ensuring the integrity and consistency of the content within their applications. As we continue to explore the Filestack integration in future articles, we’ll cover File Picker events and the user interface customization options.

To get started, sign up for a free Filestack account today and start enhancing your Froala-powered applications with a truly customized file upload experience. With Filestack’s robust file management capabilities and Froala’s industry-leading rich text editing features, you can take your content creation and management to new heights.

Get your Filestack API here for free.

Explore The Transformation Options within The Froala New File Uploading Tool

Image transformation UI

Tired of the same old image editing options in your content editor? Get ready to unlock a new world of creative possibilities with Froala’s latest file-uploading feature!

Froala integrated Filestack to bring you a powerful, user-friendly file uploader that goes way beyond basic image cropping and resizing. With the Filestack integration, you can now transform your uploaded images in ways you never thought possible – right from within the Froala editor.

Imagine being able to apply eye-catching filters, adjust the brightness and contrast, or even swap out the background of your images, all with just a few clicks. Sounds intriguing? In this post, we’ll dive into the various image transformation options available through the Filestack TUI and show you how to unleash your creative side while building content for your Froala-powered website or app.

By the end, you’ll be equipped with the knowledge to take your visual content to the next level and leave your readers thoroughly impressed. So, what are you waiting for? Let’s get started!

Getting Started with the Transformation UI

To use the Transformation UI within the Froala editor, you’ll need to follow a few simple steps:

  1. Get a Filestack API Key: Filestack is the service that powers the Transformation UI. Get a free Filestack API key now.
  2. Include the Required Scripts and Stylesheets: In your HTML file, you’ll need to include the Filestack JavaScript library, the Transformation UI scripts, and the Transformation UI stylesheet. This will give you access to all the powerful image editing tools.
  3. Configure the Froala Editor: When you initialize the Froala editor, you’ll need to provide your Filestack API key in the filestackOptions.filestackAPI setting.

Here’s an example of what your HTML code might look like:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" name="viewport" content="width=device-width, height=device-height, initial-scale=1.0,
            maximum-scale=1.0" />
        <link href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel="stylesheet"
            type="text/css" />
              <link rel="stylesheet" href="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css" />

    </head>
    <body>
        <div id="froala-editor"> </div>
        <script type="text/javascript"
            src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js"></script>
         <script src="https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js"></script>
  <script src="https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js"></script>
  <script src="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js"></script>
        
        <script>
                new FroalaEditor("div#froala-editor",{
                  filestackOptions{
                    filestackAPI: 'yourAPIKey',
                  }
                });
        </script>
        </body>
</html>

With this setup, an “Image Transformation” button will appear when you click on an image uploaded using Filestack. Clicking this button will open the Transformation UI, allowing you to edit the image in various ways before inserting it into the Froala editor.

Transformation button

If you want the Transformation UI to be available immediately after uploading an image using the “Filestack Upload” button, you can enable the transformationsUI option within the filestackOptions.pickerOptions setting.

        <script>
                new FroalaEditor("div#froala-editor",{
                  filestackOptions{
                    filestackAPI: 'yourAPIKey',
                    pickerOptions: {
                      transformationsUI: true,
                    }
                  }
                });
        </script>

Now when you click “Upload with Filestack”, you can select an image to upload. Once the image is uploaded, a thumbnail will appear, and an “Edit” button will appear on the right. Clicking the “Edit” button will open the transformation UI, allowing you to edit the image before inserting it into the editor.

Filestack upload

If you are using a front-end framework, check the following guide:

Explore Transformation UI: A Powerful Image Editing Tool

The Transformation UI is an intuitive image editing tool that appears when you click on an image uploaded using Filestack. This tool allows you to make various changes and enhancements to your images right within the Froala editor.

When you open the Transformation UI, you’ll see the image displayed in the center of the editor. At the top, you’ll find a few helpful controls:

  • Undo Button: On the left, you’ll see an “Undo” button that allows you to revert any changes you’ve made to the image.
  • Zoom Options: In the center, you’ll find zoom controls that let you adjust the size of the image within the editor.
  • Cancel and Save Buttons: On the left, you’ll see a “Cancel” button to close the editor without saving any changes, and a “Save” button to apply your edits and insert the updated image into the Froala editor.

At the bottom of the Transformation UI, you’ll find a variety of transformation options, including filters, adjustments, and overlays. Simply click on the option you want to apply it to the image. The changes will be shown in real time, so you can preview the results before finalizing your edits.

Transformation User Interface

This powerful image editing tool empowers your users to create visually stunning content with ease. By allowing them to enhance and transform their images right within the Froala editor, you’re giving them the ability to elevate the visual appeal of their content and captivate their audience.

Available Transformation Options

The Transformation UI within the Froala editor provides a range of powerful tools to enhance your images. Let’s dive into the key features:

Crop

The Crop tool allows you to select a specific area of the image and remove the unwanted parts. This is useful for focusing the viewer’s attention on the most important part of the image. You can adjust the crop box by dragging the corners or edges, and the image will update in real-time. Once you’re satisfied with the crop, simply click the “Save” button to apply the changes.

Image Crop

Froala offers several pre-defined crop options:

  • Portrait (16:9): This is ideal for social media posts, as it ensures images fit seamlessly on platforms like Instagram or Facebook.
  • Square: A square-shaped crop that you can resize and position as needed.
  • Circle: A circular crop that always maintains a perfect circle shape as you resize and position it.
  • Custom: A rectangular crop that you can freely resize and position to suit your needs.

Image crop

Resize

Resizing images is important for optimizing file size, fitting specific layouts, and ensuring consistent quality across devices. The Resize tool in the Transformation UI allows you to easily adjust the width and height of the image, while maintaining the original aspect ratio or changing it as needed. This gives you precise control over the final image size, helping you create a cohesive and visually appealing layout within the Froala editor.

Image resize

Flip and Rotate

Users often need to flip or rotate images to correct the orientation or achieve a specific visual effect. The Transformation UI provides four options for this:

  • Flip horizontally
  • Flip vertically
  • Rotate 90 degrees clockwise
  • Rotate 90 degrees counter-clockwise

Image flip and rotate

These tools empower users to optimize their images and ensure they are displayed correctly within the Froala editor.

Filters

The Transformation UI offers a variety of filters that can be applied to your images to alter their visual appeal. These filters range from subtle adjustments to dramatic effects, giving you the flexibility to find the perfect look for your content. You can experiment with different filters, adjust their intensity, and preview the changes in real time before saving the final image.

 

Enhance Presets

This feature smartly analyzes a photo and performs color correction and other enhancements to improve the overall quality of the image. You can choose from multiple presets to achieve the best results. Currently, it is available only when you open the Transformation UI from the File Picker. Here are the presets available with their purpose:

Preset Description
auto Automatically selects the best enhancement settings for a photo.
vivid Enhances depth and brightness in a photo.
beautify Ideal for portraits, this preset scans each face in the photo and adjusts corrections individually for optimal results.
beautify_plus Similar to Beautify, it applies stronger corrections with a broader range of modifications.
fix_dark It is perfect for underexposed photos or dark subjects against bright backgrounds. Turning off contrast maximizes detail in shadow areas without blowing out highlights.
fix_noise Detects and removes noise from photos while preserving details. Adjusts based on the ISO level and camera model.
fix_tint Removes abnormal tints (yellow, blue, green, etc.) caused by various lighting conditions, such as fluorescent, infrared, ultraviolet, and tungsten lights.
outdoor Enhances landscape photos by increasing color vibrancy and adjusting the contrast to reveal more detail in shadow areas.
fireworks Corrects for night skies and highlights excess colors from fireworks.

Image Adjustments

This feature allows users to adjust different image parameters to modify and enhance the visual appearance of an image. Here’s a list of different parameters you can adjust directly within the editor:

  • Blur: Softens the image, reducing detail and sharpness.
  • Brightness: Adjusts the overall lightness or darkness of the image.
  • Contrast: Alters the difference between the light and dark areas of the image.
  • Gamma: Adjusts the midtones of the image without affecting the shadows and highlights.
  • Hue: Changes the overall color tone of the image.
  • Noise: Adds or reduces random variations of brightness or color information in the image.
  • Pixelate: This creates a mosaic effect by enlarging the pixels, making the image appear blocky.
  • Saturation: Adjusts the intensity of the colors in the image.

These adjustments can be used individually or in combination to achieve the desired visual effect.

Overlay Text

The Transformation UI also allows users to overlay text on their images. This feature is useful for adding captions, titles, or other textual elements to enhance the visual communication of the content.

Users can choose from a variety of font styles, sizes, and colors, and position the text anywhere on the image. This empowers content creators to elevate their visuals and convey their message more effectively.

The text overlay tool provides a seamless way to integrate text and imagery, creating a cohesive and visually appealing final product.

Overlay Text

Overlay Image

The Transformation UI also allows users to overlay additional images on top of the main image. This can be useful for adding logos, watermarks, or other visual elements to the image. Users can resize, position, rotate, and adjust the opacity of the overlaid image to achieve the desired effect.

This feature provides a flexible way to enhance the visual impact and branding of the content within the Froala editor. The real-time preview ensures users can experiment with different overlay options and find the perfect combination.

Image Border

The Transformation UI also offers the ability to add a border around the image. Users can customize the border width, color, and style to create a polished, professional visual look.

This feature is particularly useful for framing images, separating them from the surrounding content, or adding a decorative touch. The real-time preview allows users to experiment with different border options and find the perfect balance between the image and its presentation within the Froala editor.

Elevate Your Visual Content with Froala’s Transformation UI

The Filestack integration within the Froala editor has unlocked a whole new world of creative possibilities for content creators. With the powerful Transformation UI, you now have the ability to enhance your images in ways you never thought possible – right from within your content editor.

From applying eye-catching filters and adjusting brightness and contrast, to swapping backgrounds and overlaying text and graphics, the Transformation UI puts a suite of advanced image editing tools at your fingertips. This empowers you to elevate the visual appeal of your content and leave your readers thoroughly impressed.

So what are you waiting for? Take your visual content to new heights by exploring the Transformation UI within the Froala editor. Unlock your creative potential, captivate your audience, and watch your engagement soar. Get started with the Filestack integration today and see the difference it can make for your Froala-powered website or app.

Get your Filestack API here for free.

Uploading Files to Dropbox in Angular Rich Text Editor with Froala

Froala filestack integration in Angular

Dropbox is a popular cloud storage service allowing users to securely store and share files. Integrating Dropbox with an Angular rich text editor, such as Froala, can enhance the user experience by enabling seamless file uploads directly from the editor. This integration can be achieved by leveraging a service like Filestack, which provides a user-friendly interface for handling file uploads and storage. By incorporating Filestack’s features, developers can streamline the file upload process and ensure that users can easily access and manage their Dropbox files within the rich text editor.

Froala’s latest version, V4.3, includes a new plugin for integrating with Filestack. This makes it easy to upload files to your Dropbox storage directly from the Froala editor. With just a few simple configuration steps, you can start uploading files without leaving the editor.

This integration saves development time and cost. Developers can focus on building the core functionality of their application, rather than spending time implementing complex file upload and storage solutions.

It also saves users time and effort by eliminating the need to switch between different applications or interfaces to manage files. Additionally, it ensures that uploaded files are securely stored in the user’s Dropbox account, providing an extra layer of data protection.

Overall, the Froala-Filestack-Dropbox integration offers a powerful and efficient way to incorporate file management into your Angular-based applications.

Let’s explore how this integration can be set up and leveraged to enhance your Angular application’s functionality. We’ll cover the necessary steps to configure Filestack, connect it to Dropbox, and seamlessly integrate it with the Froala rich text editor. By the end, you’ll have a robust file management solution that provides a seamless user experience within your Angular app.

Angular rich text editor

Step 1: Create a Filestack Account

You will need a Filestack account and obtain an API key for successful uploads. You can create a free Filestack account, which provides a limited amount of bandwidth, uploads, and transformations, as well as access to Filestack’s internal S3 storage. To upload files to Dropbox, you’ll need a paid plan. Start a free trial of a Filestack plan that fits your needs.

Step 2: Dropbox Configuration

Just four simple steps to ensure that files uploaded through the file picker will be stored in your Dropbox account.

  1. You need an existing Dropbox application or you can create a new one.
  2. Make sure to enable additional development users.

Enable additional users

  1. Generate an OAuth2 access token that will be added to the Dropbox storage section in the developer portal.

generate access

  1. Add the necessary policies and test the Storage Keys in the Developer Portal to ensure the connection between our API and your Cloud Storage is set.

Step 3: Create a new Angular project

Skip this step if you are installing the editor in an existing Angular project.

To create a new Angular project, you can use the Angular CLI. Open a terminal or command prompt, navigate to the desired directory, and run the following command:

ng new filestack-integration

This will create a new Angular project named “my-app” and guide you through the setup process, including options for routing and stylesheet format.

When prompted “Do you want to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)? (y/N)“, answer with “N”.

Once the project is created, you can navigate to the project directory:

cd filestack-integration

 

Step 4: Install Froala Angular SDK

To integrate the Froala rich text editor into your Angular application, you’ll need to install the Froala Angular SDK. You can do this by running the following command in your project’s root directory:

npm install angular-froala-wysiwyg --save

This will install the necessary packages and dependencies.

Step 5: Include the Froala Stylesheets

To include the necessary Froala stylesheets, add the following lines to your `angular.json` file, within the `styles` array:

"node_modules/froala-editor/css/froala_editor.pkgd.min.css",

"node_modules/froala-editor/css/froala_style.min.css"

This will ensure that the Froala editor is properly styled within your Angular application.

Step 6: Create Editor Component

In this step, we will create a custom component to handle the Froala editor and Filestack integration. This component will provide a user-friendly interface for uploading files to Dropbox directly from the rich text editor. By encapsulating the integration logic within a dedicated component, you can easily reuse and maintain the editor functionality across your Angular application.

Create a new component using the Angular CLI:

ng generate component editor

This will create a new component called EditorComponent in your project.

Step 7: Import the Froala Editor Modules

Open the editor.component.ts file and import the necessary Froala modules.

import { Component } from '@angular/core';
import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';
import 'froala-editor/js/plugins.pkgd.min.js';

@Component({
  selector: 'app-editor',
  standalone: true,
  imports: [FroalaEditorModule, FroalaViewModule],
  templateUrl: './editor.component.html',
  styleUrl: './editor.component.css'
})
export class EditorComponent {

}

Step 8: Include Filestack Files

Open index.html and include the required Filestack files to open the file picker and Transformation UI.

<link rel="stylesheet" href="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css" />

<script src="https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js"></script>

<script src="https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js"></script>

<script src="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js"></script>

Step 9: Configure the Froala Component

Open the editor.component.ts file and add the required editor configuration within the EditorComponent class. To complete the Filestack integration, consider setting the following options and events:

  • filestackOptions.filestackAPI This is where you should add your Filestack API key.
  • filestackOptions.uploadToFilestackOnly (Optional) Set this option to true if you want to handle all file uploads by Filestack.
  • filestackOptions.pickerOptions (Optional) Use this option to customize the Filestack Picker.
  • filestack.filestackPickerOpened (Optional) This event is triggered when the Filestack File Picker is opened.
  • filestack.filestackPickerClosed (Optional) This event is triggered when the Filestack File Picker is closed.
  • filestack.uploadedToFilestack (Optional) This event is triggered when files are successfully uploaded to your storage.
  • filestack.uploadFailedToFilestack (Optional) This event is triggered when a file upload fails. You can use this event to run a custom function to handle the failed upload.
import { Component } from '@angular/core';
import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';
import 'froala-editor/js/plugins.pkgd.min.js';

@Component({
  selector: 'app-editor',
  standalone: true,
  imports: [FroalaEditorModule, FroalaViewModule],
  templateUrl: './editor.component.html',
  styleUrl: './editor.component.css'
})
export class EditorComponent {
  public editorContent = "Filestack is a simple file uploader & powerful APIs to upload, transform & deliver any file into your app.";
  public options: Object = {

    heightMin: 300,
    filestackOptions: {
      uploadToFilestackOnly: true,
      filestackAPI: "AvaZ2E0mxRdGPjgMAbus8z",
    },

    events: {
      'filestack.uploadedToFilestack': function () {
        console.log("Callback is triggered for uploaded to filestack ",)
      },

      'filestack.filestackPickerOpened': function () {
        console.log("Callback is triggered for picker opened ",)
      },

      'filestack.filestackPickerClosed': function () {
        console.log("Callback is triggered for picker closed ",)
      },

      'filestack.uploadFailedToFilestack': function () {
        console.log("Callback is triggered for filestack failed ",)
      },

    },
  };
}

Then add <div [froalaEditor]="options" [(froalaModel)]="editorContent"></div> in your editor.component.html file.

With the editor component set up, you can now use it in your Angular application. Simply add the <app-editor> element wherever you want the rich text editor to appear. The EditorComponent will handle the integration with Froala and Filestack, providing a seamless user experience for file uploads directly within the editor. The uploaded files will then be stored in Dropbox using the Filestack integration. This allows your users to easily incorporate multimedia content into their rich text content without leaving the editor interface.

Step 10: Displaying Froala on the main page

To display the Froala editor on the main page of your Angular application, open app.component.ts and import the EditorComponent.

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { EditorComponent } from './editor/editor.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet, EditorComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'filestack-integration';
}

Then simply add the <app-editor> element to the app.component.html template.

<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * The content below * * * * * * * * * * * -->
<!-- * * * * * * * * * * is only a placeholder * * * * * * * * * * -->
<!-- * * * * * * * * * * and can be replaced.  * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * Delete the template below * * * * * * * * * -->
<!-- * * * * * * * to get started with your project! * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->

<style>
  :host {
    --bright-blue: oklch(51.01% 0.274 263.83);
    --electric-violet: oklch(53.18% 0.28 296.97);
    --french-violet: oklch(47.66% 0.246 305.88);
    --vivid-pink: oklch(69.02% 0.277 332.77);
    --hot-red: oklch(61.42% 0.238 15.34);
    --orange-red: oklch(63.32% 0.24 31.68);

    --gray-900: oklch(19.37% 0.006 300.98);
    --gray-700: oklch(36.98% 0.014 302.71);
    --gray-400: oklch(70.9% 0.015 304.04);

    --red-to-pink-to-purple-vertical-gradient: linear-gradient(180deg,
        var(--orange-red) 0%,
        var(--vivid-pink) 50%,
        var(--electric-violet) 100%);

    --red-to-pink-to-purple-horizontal-gradient: linear-gradient(90deg,
        var(--orange-red) 0%,
        var(--vivid-pink) 50%,
        var(--electric-violet) 100%);

    --pill-accent: var(--bright-blue);

    font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
      Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
      "Segoe UI Symbol";
    box-sizing: border-box;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }

  h1 {
    font-size: 3.125rem;
    color: var(--gray-900);
    font-weight: 500;
    line-height: 100%;
    letter-spacing: -0.125rem;
    margin: 0;
    font-family: "Inter Tight", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
      Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
      "Segoe UI Symbol";
  }

  p {
    margin: 0;
    color: var(--gray-700);
  }

  main {
    width: 100%;
    min-height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    box-sizing: inherit;
    position: relative;
  }


  .content {
    display: flex;
    justify-content: space-around;
    width: 100%;
    max-width: 700px;
    margin-bottom: 3rem;
  }

  .content p {
    margin-top: 1.5rem;
  }


  @media screen and (max-width: 650px) {
    .content {
      flex-direction: column;
      width: max-content;
    }

  }
</style>

<main class="main">
  <div class="content">
    <div class="">

      <p>Congratulations! Your app is running. 🎉</p>
      <app-editor></app-editor>
    </div>

  </div>
</main>

<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * The content above * * * * * * * * * * * * -->
<!-- * * * * * * * * * * is only a placeholder * * * * * * * * * * * -->
<!-- * * * * * * * * * * and can be replaced.  * * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * End of Placeholder  * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->


<router-outlet></router-outlet>

This will render the EditorComponent you created earlier, which encapsulates the Froala editor and Filestack integration. By using the custom EditorComponent, you can easily reuse the rich text editing functionality across your application without having to manage the integration details in multiple places. This promotes code reusability and maintainability as your application grows.

Step 11: Test your App

Run ng serve. This will start the development server and make your Angular application available at http://localhost:4200

Forala Filestack Integration in Angular

You can now test the Froala editor and Filestack integration within your Angular application. Verify that the editor is displayed correctly on the main page and that users can upload files directly within the editor interface. Ensure that the uploaded files are successfully stored in Dropbox using the Filestack integration.

forala angular rich text editor with Filestack integration Froala Angular WYSIWYG editor integration with Filestack Froala integration with Dropbox

Test various editing features provided by Froala, such as formatting, inserting images, and embedding multimedia content. Validate that the rich text content is properly rendered and that the user experience is seamless. Make any necessary adjustments to the integration or styling to optimize the overall functionality and appearance of the editor within your Angular application.

Elevate Your Angular App with Seamless Dropbox Integration

By integrating Froala’s Angular rich text editor with Filestack and Dropbox, you can elevate your Angular application’s functionality and provide users with a seamless content creation experience. This integration empowers your users to effortlessly upload and manage files directly within the editor, eliminating the need to switch between different applications.

The benefits of this integration are clear:

  • It saves development time and costs, while also enhancing the user experience.
  • Developers can focus on building core application features, rather than implementing complex file upload and storage solutions.
  • Users enjoy the convenience of accessing and managing their Dropbox files without leaving the familiar Froala editor interface.

Don’t settle for a disjointed content creation workflow in your Angular app. Embrace the power of the Froala-Filestack-Dropbox integration and take your application to new heights.

Get your Filestack API here for free.

How to transform your LMS with a React WYSIWYG HTML editor, part 1

We’ve all been there. Huge project, impending deadlines, hopeful clients or investors, and plenty of tasking tasks left. Uploading content like rich text with images, videos, and specific formatting, for example, is not as simple as it sounds. This is especially true for LMS (learning management systems), which require course creators to upload different content in one go. To accommodate this need, we must prepare to allow as many file types as possible while also considering rich text processing and storage. Thankfully, we have WYSIWYG editors for that. In this tutorial, we’ll tackle these LMS content issues using a React WYSIWYG HTML editor.

Key takeaways

  • A WYSIWYG HTML editor significantly simplifies content processing and uploading tasks
  • Video and image uploads, processing, and transformations make LMS more engaging and powerful.
  • Froala Editor now comes with built-in Filestack integration, making image transformations and more possible within the editor.
  • You can use React, PHP (or the back-end tool of your choice), and Froala to easily get started with a modern LMS project.
  • As your mastery with WYSIWYG editors and file upload tools grows, so do the capabilities of your LMS.

Defining the scope and features of our LMS project

First, let me clarify that this isn’t a full tutorial for creating a full-fledged LMS. Instead, this is a guide for those who want to have robust content editing and uploading features within their projects. We will be building the front end of the application using React and Froala. For file uploading, we’ll leverage the newly integrated Filestack within the editor. Finally, we will use PHP for the back-end parts and SQL Server for storing and retrieving the data.

Our mini LMS will have the following features:

  • View and add courses – each course will have a title, description, date published, and a unique ID.
  • View and add chapters – each course will consist of chapters, which contain a title, description, content, date published, and a unique ID.

We’ll first set up the React application and Froala Editor. And then, we will create the front end of the application, followed by the back end and database tables. In the end, we’ll run a demo of the application.

Setting up the React project and the WYSIWYG HTML editor

Let’s start our project by creating our React app and installing the packages that we need:  

npx create-react-app demo-lms
cd demo-lms
npm install react-froala-wysiwyg --save

npm install react-router-dom

 

Now, you should have a React application with the Froala WYSIWYG HTML editor and page routing dependencies. The next thing we need to do is create a new folder under “src” called “components.” Afterwards, create a new file named “FroalaComponent.jsx” and insert the following:

import React, { useEffect } from 'react';
import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/css/froala_editor.pkgd.min.css';
import FroalaEditorComponent from 'react-froala-wysiwyg';
import 'froala-editor/js/plugins.pkgd.min.js';

function FroalaComponent({ setChapterContent, setChapterImage }) {
  const config = {
    filestackOptions: {
      uploadToFilestackOnly: true,
      filestackAPI: 'InsertYourFilestackAPIHere',
    },
    events: {
      'contentChanged': function () {
        setChapterContent(this.html.get());
      },
      'filestack.uploadedToFilestack': function (response) {
        if(response && response.filesUploaded[0].url){
          setChapterImage(response.filesUploaded[0].url);
        }

        else{
          console.error("Image upload failed, no URL found in response", response);
        }
      }
},
  };

  useEffect(() => {
    const filestackScript1 = document.createElement('script');
        filestackScript1.src = 'https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js';
        filestackScript1.async = true;
        document.body.appendChild(filestackScript1);

        const filestackScript2 = document.createElement('script');
        filestackScript2.src = 'https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js';
        filestackScript2.async = true;
        document.body.appendChild(filestackScript2);

        const filestackScript3 = document.createElement('script');
        filestackScript3.src = 'https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js';
        filestackScript3.async = true;
        document.body.appendChild(filestackScript3);

        const filestackStylesheet = document.createElement('link');
        filestackStylesheet.rel = 'stylesheet';
        filestackStylesheet.href = 'https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css';
        document.head.appendChild(filestackStylesheet);

    return () => {
      document.body.removeChild(filestackScript1);
      document.body.removeChild(filestackScript2);
      document.body.removeChild(filestackScript3);
      document.head.removeChild(filestackStylesheet);
    };
  }, []);

  return (
    <div className="editor">
      <FroalaEditorComponent tag='textarea' config={config} />
    </div>
  );
}

export default FroalaComponent;

The first thing we need to do is declare our component and its properties. Note that for the Froala config, we have to declare the Filestack options, including our Filestack API. You can get one by creating a free Filestack account or starting a free trial of a paid plan. Also note that we’re handling Froala’s content-change events and Filestack’s image upload event. This is for storing a course chapter’s content and image URL later.

Additionally, we’re loading Filestack-related scripts and styles dynamically using useEffect. That way, we can easily use Filestack’s drag-and-drop functionality, image uploads, and other features. Lastly, we load our FroalaEditorComponent and its configuration. If you need additional guidance on setting up Froala for React, follow this helpful article.

Creating the LMS

Now that we have the application and our Froala WYSIWYG HTML editor component ready, let’s build our LMS! Start by creating 4 files under the components folder:

  • Courses.jsx: For viewing courses and navigating to a course’s chapters
import React, { useState, useEffect } from 'react';
import CourseModal from './CourseModal';
import { Link } from 'react-router-dom';

function Courses() {
  const [courses, setCourses] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const fetchCourses = async () => {
    // Fetch courses from the back end
    const response = await fetch('path-to-backend/demo-lms-backend/fetchCourses.php');
    const data = await response.json();
    setCourses(data);
  };

  useEffect(() => {
    fetchCourses();
  }, []);

  const handleSaveCourse = () => {
    fetchCourses(); // Fetch courses again after saving a new one
    setIsModalOpen(false);
  };

  return (
    <div className="course-list">
      <h1>My Simple yet Powerful LMS</h1>
      <h2>Courses</h2>

      <button onClick={() => setIsModalOpen(!isModalOpen)}>
        {isModalOpen ? 'Close' : 'Add a Course'}
      </button>

      {isModalOpen && <CourseModal onSaveCourse={handleSaveCourse} onClose={() => setIsModalOpen(false)} />}
      {courses.map((course) => (
        <div key={course.course_id} className="course-card">
          <h3>{course.course_title}</h3>
          <p>{course.course_description}</p>
          <p>Date Published: {course.date_published ? new Date(course.date_published.date).toLocaleDateString() : 'N/A'}</p>
          <Link to={`/chapters/${course.course_id}`}>
            <button>View Course</button>
          </Link>
        </div>
      ))}
    </div>
  );
}

export default Courses;
  • CourseModal.jsx: For saving courses
import React, { useState } from 'react';

function CourseModal({ onSaveCourse, onClose }) {
  const [courseTitle, setCourseTitle] = useState('');
  const [courseDescription, setCourseDescription] = useState('');

  const handleSubmitCourse = async (e) => {
    e.preventDefault();

    const newCourse = {
      title: courseTitle,
      description: courseDescription,
      date_published: new Date().toISOString().split('T')[0],
    };

    const response = await fetch('path-to-backend/demo-lms-backend/saveCourse.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(newCourse),
    });

    const result = await response.json();
    if (response.ok) {

      // This will call fetchCourses from Courses.jsx
      onSaveCourse();
    } else {
      console.error('Failed to save course:', result);
    }
  };

  return (
    <div className="modal">
      <form onSubmit={handleSubmitCourse}>
        <h3>New Course</h3>
        <label>Title</label>
        <input type="text" value={courseTitle} onChange={(e) => setCourseTitle(e.target.value)} required />
     
        <label>Description</label>
        <textarea value={courseDescription} onChange={(e) => setCourseDescription(e.target.value)} required />

        <button type="submit">Save</button>
        <button type="button" onClick={onClose}>Cancel</button>
      </form>
    </div>
  );
}

export default CourseModal;
  • Chapters.jsx: For viewing the chapters of a course and navigating back to the courses
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import ChapterModal from './ChapterModal';
import { Link } from 'react-router-dom';

function Chapters() {
  const { courseId } = useParams();
  const [chapters, setChapters] = useState([]);
  const [course, setCourse] = useState(null); // To store course details
  const [isModalOpen, setIsModalOpen] = useState(false);

  // Fetch chapters for the course
  const fetchChapters = async () => {
    const response = await fetch(`path-to-backend/demo-lms-backend/fetchChapters.php?course_id=${courseId}`);
    const data = await response.json();
    setChapters(data);
  };

  // Fetch course details
  const fetchCourseDetails = async () => {
    const response = await fetch(`path-to-backend/demo-lms-backend/getCourseById.php?courseId=${courseId}`);
    const data = await response.json();
    setCourse(data);
  };

  useEffect(() => {
    fetchChapters();
    fetchCourseDetails(); // Fetch course details on load
  }, [courseId]);

  const handleSaveChapter = (newChapter) => {
    setChapters([...chapters, newChapter]);
    setIsModalOpen(false);
  };

  if (!course) {
    return <p>Loading course details...</p>;
  }

  return (
    <div className="course-details">
      <h1>{course.course_title}</h1>
      <p>Description: {course.course_description}</p>
      <p>Date Published: {course.date_published ? new Date(course.date_published.date).toLocaleDateString() : 'N/A'}</p>
      <Link to={`/`}>
        <button>Back to Courses</button>
      </Link>

      <button onClick={() => setIsModalOpen(!isModalOpen)}>
        {isModalOpen ? 'Close' : 'Add a Chapter'}
      </button>
   
      <div className="chapter-list">
        {chapters.map((chapter) => (
          <div key={chapter.chapter_id} className="chapter-card">
            <h3>{chapter.chapter_title}</h3>
            <p>{chapter.chapter_description}</p>
            <p>Date Published: {chapter.date_published}</p>
          </div>
        ))}
      </div>

      {isModalOpen && <ChapterModal courseId={courseId} onSaveChapter={handleSaveChapter} onClose={() => setIsModalOpen(false)} />}
    </div>
  );
}

export default Chapters;
  • ChapterModal.jsx: For saving chapters within a course
import React, { useState } from 'react';
import FroalaComponent from './FroalaComponent';

function ChapterModal({ courseId, onSaveChapter, onClose }) {
  const [chapterTitle, setChapterTitle] = useState('');
  const [chapterDescription, setChapterDescription] = useState('');
  const [chapterContent, setChapterContent] = useState('');
  const [chapterImage, setChapterImage] = useState('');

  const handleSubmitChapter = async (e) => {
    e.preventDefault();

    console.log('Chapter Image URL:', chapterImage);

    const newChapter = {
      course_id: courseId,
      title: chapterTitle,
      description: chapterDescription,
      content: chapterContent,
      chapter_img: chapterImage, // for Filestack URL
      date_published: new Date().toISOString().split('T')[0],
    };

    const response = await fetch('path-to-backend/demo-lms-backend/saveChapter.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(newChapter),
    });

    const result = await response.json();
    if (response.ok) {
      onSaveChapter(result);
    } else {
      console.error('Failed to save chapter:', result);
    }
  };

  return (
    <div className="modal">
      <form onSubmit={handleSubmitChapter}>
        <h3>Add New Chapter</h3>
        <label>Title</label>
        <input type="text" value={chapterTitle} onChange={(e) => setChapterTitle(e.target.value)} required />
     
        <label>Description</label>
        <textarea value={chapterDescription} onChange={(e) => setChapterDescription(e.target.value)} required />
     
        <label>Content</label>
        <FroalaComponent setChapterContent={setChapterContent} setChapterImage={setChapterImage} />

        <div><button type="submit">Save</button> <button type="button" onClick={onClose}>Cancel</button></div>
      </form>
    </div>
  );
}

export default ChapterModal;

Lastly, replace the default code in your App.js with:

import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import './App.css';
import Courses from './components/Courses';
import Chapters from './components/Chapters';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Courses />} />
        <Route path="/chapters/:courseId" element={<Chapters />} />
      </Routes>
    </Router>
  );
}

export default App;

Here’s a quick summary of how our components work:

  • App.js displays the Courses page first. Using the fetchCourses function, the application will send a fetch request to fetchCourses.php on the server. This loads all courses from the database table.
  • When the user clicks the “Add a Course” button, we’ll show the CourseModal component. The user can then save a course through a fetch request to saveCourse.php. After saving the course, the application refreshes the courses.
  • The Chapters and ChapterModal components work similarly, except that loading and saving chapter data requires a course ID. Furthermore, we add the Froala component in our ChapterModal.

After creating the front end of our LMS, we’ll handle the back end of the application next.

Setting up the DB tables and back-end codes

For our database tables, we’ll create two simple tables in SQL Server:

  • course
    • course_id char(10)
    • course_title varchar(100)
    • course_description varchar(255)
    • date_published date
  • chapter
    • course_id char(10)
    • chapter_id char(10)
    • chapter_title varchar(100)
    • chapter_description varchar(255)
    • chapter_content varchar(max)
    • chapter_img_url varchar(255)
    • date_published date

These are just some basic tables, so you will want to improve this or plan ahead when implementing your LMS. Note that we plan to store the contents of the editor in chapter_content. On the other hand, we’ll store the Filestack URL in the chapter_img_url column. For now, we choose 255 as the max length, but you might want to adjust this in your implementation.

Alright, we’re almost done! The last thing we need to do is create our PHP files for fetching and saving data. We also assume that we have a “connection.php” that connects to a database instance. Here are our PHP files and their respective purposes:

  • fetchCourses.php: Retrieve all course data from the course table
<?php
    include "connection.php";

    $query = "SELECT course_id, course_title, course_description, date_published FROM course";
    $result = sqlsrv_query($conn, $query);

    $courses = array();
    while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
        $courses[] = $row;
    }

    sqlsrv_close($conn);
    echo json_encode($courses);
?>
  • saveCourse.php: Generate a unique course ID and save the course data
<?php
    include "connection.php";

    $input = json_decode(file_get_contents("php://input"), true);

    $course_title = $input["title"];
    $course_description = $input["description"];

    $query = "
        DECLARE @course_id CHAR(10)

        WHILE 1 = 1
        BEGIN
            SET @course_id = LEFT(CONVERT(NVARCHAR(36), NEWID()), 10)

            IF NOT EXISTS (SELECT 1 FROM course WHERE course_id = @course_id)
            BEGIN
                BREAK
            END
        END

        INSERT INTO course
        (course_id, course_title, course_description, date_published)
        VALUES
        (@course_id, ?, ?, GETDATE())
    ";
    $params = array($course_title, $course_description);
    $result = sqlsrv_query($conn, $query, $params);

    if($result===false) {
        echo json_encode(["error" => "Failed to save course"]);
    }
    else{
        echo 1;
    }
    sqlsrv_close($conn);
?>
  • getCourseById.php: Select all information of a specific course (for generating course data in our Chapters component)
<?php
    include "connection.php";

    if (isset($_GET["courseId"])) {
        $courseId = $_GET["courseId"];

        $query = "SELECT course_id, course_title, course_description, date_published FROM course WHERE course_id = ?";
        $params = array($courseId);
        $stmt = sqlsrv_query($conn, $query, $params);

        if($stmt === false){
            http_response_code(500);
            echo json_encode(["error" => "Failed to query the database."]);
            exit;
        }

        $course = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);

        if($course){
            echo json_encode($course);
        }
        else{
            http_response_code(404);
            echo json_encode(["message" => "Course not found"]);
        }

        sqlsrv_free_stmt($stmt);
        sqlsrv_close($conn);
    }
    else{
        echo json_encode(["message" => "Course ID not provided"]);
    }
?>
  • fetchChapters.php: Get all chapters in a course
<?php
    include "connection.php";

    $course_id = $_GET["course_id"];

    $query = "SELECT chapter_title, chapter_description, date_published FROM chapter WHERE course_id = ?";
    $params = array($course_id);
    $result = sqlsrv_query($conn, $query, $params);

    if ($result === false) {
        die("Error in query preparation/execution: " . print_r(sqlsrv_errors(), true));
    }
    $chapters = array();
    while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
        $chapters[] = $row;
    }

    sqlsrv_close($conn);
    echo json_encode($chapters);
?>
  • saveChapter.php: Add a chapter to a course
<?php
    include "connection.php";

    $input = json_decode(file_get_contents("php://input"), true);

    $course_id = $input["course_id"];
    $chapter_title = $input["title"];
    $chapter_description = $input["description"];
    $chapter_content = $input["content"];
    $chapter_img_url = $input["chapter_img"];

    $query = "
        DECLARE @chapter_id CHAR(10)

        WHILE 1 = 1
        BEGIN
            SET @chapter_id = LEFT(CONVERT(NVARCHAR(36), NEWID()), 10)

            IF NOT EXISTS (SELECT 1 FROM chapter WHERE chapter_id = @chapter_id)
            BEGIN
                BREAK
            END
        END

        INSERT INTO chapter
        (course_id, chapter_id, chapter_title, chapter_description, chapter_content, chapter_img_url, date_published)
        VALUES
        (?, @chapter_id, ?, ?, ?, ?, GETDATE())
    ";

    $params = array($course_id, $chapter_title, $chapter_description, $chapter_content, $chapter_img_url);
    $result = sqlsrv_query($conn, $query, $params);

    if($result===false){
        echo json_encode(["error" => "Failed to save chapter"]);
    }
    else{
        echo 1;
    }
    sqlsrv_close($conn);
?>

And that’s it! Now, we have all we need for our React LMS with image transformations and rich-text editing. 

Seeing the React WYSIWYG HTML editor LMS in action

Let’s end this tutorial by checking how our React LMS works. After running npm start, we’ll see the homepage, which is empty at first. So, let’s add a course:

A GIF showing the sample LMS' feature that allows users to create courses.

We now have a course. Note that for demo purposes, we didn’t apply that much CSS for now, which is why the input fields and other elements look out of place. Next, let’s view the course and try to add a chapter. After clicking “Add a Chapter,” we will see the WYSIWYG HTML editor along with two input fields.

A GIF showing how you can create an LMS chapter for a course using Froala, Filestack, and React.

Once we’ve selected, cropped, and uploaded the image through the integrated Filestack file picker, we’ll now apply some transformations to the image.

A GIF showing how you can transform images using Froala's built-in Filestack file picker.

Lack of CSS aside, this LMS already looks and feels like a top-notch editing and content processing tool because of the WYSIWYG editor. Lastly, we save the enhanced image, insert a document (a sample chapter outline), add the chapter title and description, and save the chapter.

A GIF that shows how you can upload documents using Froala and Filestack.

Now, let’s check the database to see if we saved the information correctly. Note that I added the chapter to the course about 4 days after creating the course.

Database results that show correctness in terms of data uploaded

Let’s also check our Filestack dashboard:

We can see that we have both the edited image and our demo PDF in our Filestack dashboard. If we now download the image file, we’ll see the image that we transformed earlier in our LMS!

An image that was uploaded using Froala Editor and cropped and edited using Filestack

And there you have it: a React WYSIWYG HTML editor-powered LMS. Undoubtedly, this is far from a finished or even decent LMS product. However, it’s a good start, especially if you plan on implementing comprehensive image handling and content editing on your application. Moreover, we can still do a lot more that I haven’t shown you yet. Next time, we’ll continue this mini project and load the image from Filestack back to our application. Happy coding!

Get your Filestack API here for free.

Integrating Google Cloud Storage in Vue.js Rich Text Editor with Froala

Froala Vue.js rich text editor

As businesses continue to embrace the power of cloud computing, the need to effortlessly manage and store files has become paramount. If you’re a Vue.js developer working with the Froala rich-text editor, you may have encountered the challenge of implementing a file-uploading process that seamlessly integrates with Google Cloud Storage.

Fortunately, the latest version of Froala, V4.3, has introduced a game-changing solution: the Filestack plugin. This innovative feature makes integrating your Vue.js WYSIWYG editor with Google Cloud Storage a breeze, requiring only a few lines of code to set up.

In this article, we’ll dive deep into how Froala V4.3 has simplified this process, empowering you to effortlessly store your files in the Google Cloud while providing your users with a seamless rich-text editing experience. We will discover practical insights and step-by-step guidance to help you master this powerful integration.

So, let’s explore how you can elevate your Vue.js projects by seamlessly connecting your Froala rich-text editor with the reliability and scalability of Google Cloud Storage.

Wysiwyg editor with Google cloud integration

How does Froala V4.3 simplify the integration with Google Cloud?

Froala V4.3 introduces a game-changing feature that streamlines the process of integrating your Vue.js rich-text editor with Google Cloud Storage. This new capability comes in the form of the Filestack plugin, which seamlessly integrates the Filestack Picker directly into the Froala editor.

With the Filestack plugin, users can now upload images, videos, and files directly from the rich-text editor, and these assets will be automatically stored in your Google Cloud Storage. This is made possible by the Filestack platform, which supports a wide range of popular cloud storage services, including Google Cloud.

The integration process is incredibly straightforward. All you need to do is connect your Google Cloud account to your Filestack dashboard, and you’re good to go. From that point on, any files uploaded through the Filestack Picker within the Froala editor will be directly saved to your Google Cloud Storage, without the need for any additional configuration or complex integrations.

This streamlined approach not only saves you time and effort but also ensures a seamless user experience for your content creators. They can focus on crafting their content, while the Froala-Filestack-Google Cloud integration handles the behind-the-scenes file management, allowing you to leverage the power and reliability of Google Cloud Storage with minimal hassle.

Let’s explore how this integration works.

Step 1: Create a simple Vue project

Skip this step if you will install the editor in an existing Vue app.

Run the following commands to create a new Vue 3 project.

npm install -g @vue/cli

vue create my-froala-vue-app

cd my-froala-vue-app

The above code creates a new Vue 3 project named “my-froala-vue-app” and navigates to the project directory. This provides a clean starting point for integrating the Froala rich-text editor and enabling the Google Cloud Storage integration using the Filestack plugin.

Step 2: Install the Froala Editor Vue SDK

Next, you’ll need to install the Froala Editor for Vue.js. Run the following commands in your project directory:

npm install vue-froala-wysiwyg --save

This will add the required dependencies to your project, allowing you to use the Froala editor within your Vue application.

Step 3: Include Froala in Your Application

3.1 Import Froala Editor in main.js

In your “main.js” file, import the Froala associated CSS and JS files:

import { createApp } from 'vue'
import App from './App.vue'

//Import Froala Editor plugins
import 'froala-editor/js/plugins.pkgd.min.js';


// Import Froala Editor css files.
import 'froala-editor/css/froala_editor.pkgd.min.css';
import 'froala-editor/css/froala_style.min.css';


// Import Froala Editor component
import VueFroala from 'vue-froala-wysiwyg';

const app = createApp(App);          

app.use(VueFroala);
app.mount('#app');

This step ensures that the Froala Editor is available throughout your Vue.js application, allowing you to use it in your components.

3.2 Use Froala in a Vue Component

In your “App.vue” file, add the Froala component within the template and add some initial configuration.

<template>

  <froala id="edit" :tag="'textarea'" :config="config" v-model:value="model"></froala>

</template>


<script>

export default {

  name: 'App',

  data () {

    return {

      config: {

        heightMin: 300,

      },

      model: '<i>Edit Your Content Here!</i>'

    }

  }

}

</script>


<style>

#app {

  font-family: Avenir, Helvetica, Arial, sans-serif;

  -webkit-font-smoothing: antialiased;

  -moz-osx-font-smoothing: grayscale;

  text-align: center;

  color: #2c3e50;

  margin-top: 60px;

}

</style>

The Froala component has three attributes:

  • :tag attribute is used to tell on which tag the editor is initialized.
  • :config attribute is used to configure the editor options.
  • v-model:value Used to load editor content. This value is affected by editor HTML changes.

Step 4: Include Filestack for Uploading and Storing Files

Since we already included the “plugins.pkgd.min.js” file in our application, then the Froala Filestack is already included and active by default. However, to correctly display the Filestack File Picker and UI Transformation tools in the editor, include the following Filestack stylesheet and scripts:

Open the “public/index.html” file and include the mentioned scripts.

<!DOCTYPE html>
<html lang="">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <link rel="icon" href="<%= BASE_URL %>favicon.ico">
  <title>
    <%= htmlWebpackPlugin.options.title %>
  </title>
  <link rel="stylesheet" href="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css" />

</head>

<body>
  <noscript>
    <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
        Please enable it to continue.</strong>
  </noscript>
  <div id="app"></div>
  <!-- built files will be auto injected -->
  <script src="https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js"></script>
  <script
    src="https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js"></script>
  <script src="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js"></script>
</body>

</html>

Step 5: Create a Filestack Account

To integrate the Filestack File Picker with your Froala Editor, you’ll need to create a Filestack account and obtain an API key.

  1. Sign up for a Filestack Account:
    You can create a free Filestack account with low bandwidth, uploads, transformations, and storage limits. However, to upload files to Google Cloud you need a paid plan. Start a free trial of a paid plan based on your needs.
  2. Obtain the Filestack API Key:
    • After creating your account, you’ll be taken to the Filestack dashboard.
    • In the dashboard, locate the “API Keys” section and copy your “API Key”.
    • You’ll need this API key to configure the Filestack integration with your Froala Editor.

Get Filestack API key

With your Filestack account and API key, you’re now ready to integrate the Filestack File Picker into your Froala Editor, allowing your users to upload, store, and transform files directly within the rich-text editing experience.

Step 6: Filestack Configuration

To complete the Filestack integration, we need to configure the following options and events:

  • Set the filestackOptions.filestackAPI to your Filestack API key.
  • (Optional) Set the filestackOptions.uploadToFilestackOnly to true. This will handle all file uploads by Filestack.
  • (Optional) Pass the File Picker configurations in the filestackOptions.pickerOptions option to customize the Filestack Picker.
  • (Optional) Configure the filestack.filestackPickerOpened event. This allows you to execute a custom action after a user opens the Filestack File Picker.
  • (Optional) Configure the filestack.filestackPickerClosed event. This allows you to execute a custom action after a user closes the Filestack File Picker.
  • (Optional) Configure the filestack.uploadedToFilestack event. This allows you to execute a custom action when files are successfully uploaded to your cloud storage.
  • (Optional) Configure the filestack.uploadFailedToFilestack event. This allows you to execute a custom action if the file upload fails.

Open your “App.vue” file and modify the data() function:

      data () {
      
        return {
        
          config: {
            
            heightMin: 300,
            filestackOptions: {
              uploadToFilestackOnly: true,
              filestackAPI: "***",
            },

            events: {
              'filestack.uploadedToFilestack': function () {
                  console.log("Callback is triggered for uploaded to filestack ",)
              },

              'filestack.filestackPickerOpened': function () {
                  console.log("Callback is triggered for picker opened ",)
              },

              'filestack.filestackPickerClosed': function () {
                  console.log("Callback is triggered for picker closed ",)
              },

              'filestack.uploadFailedToFilestack': function () {
                  console.log("Callback is triggered for file stack failed ",)
              },

            },
          },
        
          model: '<i>Edit Your Content Here!</i>'
        
        }
      
      }

Step 7: Google Cloud Configuration

Log in to your Filestack Dev Portal to configure your storage options so that uploaded files are saved in your Google Cloud account instead of Filestack’s default S3 bucket.

Simply add your service account key and ensure it has the Storage Object Admin role.

Note that depending on your internal GCS settings, additional permissions may be required, such as Storage Admin, Storage Object Creator, and Storage Object Viewer.

Obtain the JSON key for this account and paste it into the Access Key field in the GCS section of the developer portal.

Step 8: Start Your Application

With the Filestack integration and Google Cloud Storage configuration complete, you can now start your application. Run the following command in your terminal:

npm run serve

This command will start the development server and run your application at “http://localhost:8080”.

Froala Filestack integration

When a user clicks the Filestack File Picker button, the picker will open, allowing them to select files from various sources. The selected files will be automatically uploaded to your Google Cloud Storage account, and you can handle the successful or failed upload events using the configured callbacks. This integration provides a seamless file management experience within your Froala Editor-powered application.

What other cloud storage services are supported?

In addition to Google Cloud Storage, Filestack supports integration with other popular cloud storage services such as Amazon S3, Rackspace, Microsoft Azure Blob Storage, and Dropbox. You can configure the desired cloud storage provider in the Filestack Developer Portal and use the same integration approach as outlined for Google Cloud Storage. This flexibility allows you to choose the cloud storage solution that best fits your application’s requirements and infrastructure. The Filestack File Picker seamlessly handles file uploads and transformations, regardless of the underlying cloud storage provider.

Unlock the Power of Seamless Cloud Integration with Froala, Filestack, and Google Cloud Storage

By leveraging the Filestack plugin in Froala V4.3, you can now effortlessly integrate your Vue.js rich-text editor with the reliability and scalability of Google Cloud Storage. This game-changing integration empowers your content creators to focus on crafting exceptional content, while the behind-the-scenes file management is handled seamlessly.

With just a few lines of code, you can set up this powerful integration and unlock a new level of productivity and efficiency in your Vue.js projects. Say goodbye to the hassle of complex file upload processes and hello to a streamlined, user-friendly experience that delights your users.

Get your Filestack API here for free.

React Rich-Text Editor with Advanced Images and Cloud Storage

React rich-text editor

Rich-text editor is a crucial component that allows your users to seamlessly add and edit content. But have you ever found the process of integrating image uploads and storage to be a complex and time-consuming task?

Rich-text editors are undoubtedly popular, but the ability to easily insert and display images is often a pain point. Traditionally, developers have had to write additional code to handle the uploading and storage of images, a process that can be both tedious and error-prone.

However, thanks to the integration between Froala and Filestack, introduced in Froala version 4.3, the uploading and storing of any type of files has become a straightforward process. In this article, we’ll guide you through the setup of this powerful integration within your React applications, empowering you to create a React rich-text editor with advanced image editing capabilities and a seamless cloud storage solution.

Get ready to streamline your content management workflow and provide your users with a truly exceptional experience. Let’s dive in and explore how you can leverage this powerful combination to take your web applications to new heights.

A React Rich-Text Editor with Advanced Image Capabilities and Seamless Cloud Storage Solution

Step 1: Creating A React App.

Skip this step if you will install the editor in an existing React app.

Run the following commands to create a new React application

npm install -g create-react-app

npx create-react-app froala-app

cd froala-app

The above code creates a new React application named “froala-app” and navigates to the project directory. This sets up the necessary files and folders for a basic React application, which you can then customize to integrate the Froala Rich Text Editor and Filestack for file management.

Step 2: Install Froala React Component

Next, you’ll need to install the Froala Rich Text Editor SDK for React. Run the following commands in your project directory:

npm install react-froala-wysiwyg --save

This will add the required dependencies to your project, allowing you to use the Froala editor within your React application.

Step 3: Include Froala in Your Application

To create a Froala editor component with your custom configuration, create a new file “src/components/FroalaComponent.jsx” and add the following code

import React from 'react';

// Require Editor CSS files.

import 'froala-editor/css/froala_style.min.css';

import 'froala-editor/css/froala_editor.pkgd.min.css';

import FroalaEditorComponent from 'react-froala-wysiwyg';

import 'froala-editor/js/plugins.pkgd.min.js';

// Render Froala Editor component.
function FroalaComponent (){

  return (
  
    <div class="editor">
    
    <h3> Froala's React WYSIWYG Editor</h3>
    
    <FroalaEditorComponent tag='textarea'/>
    
    </div>
  
  );

}

export default FroalaComponent;

In the above code, we did the following

  • Import the necessary Froala CSS files and the FroalaEditorComponent from the “react-froala-wysiwyg” library.
  • Import the /plugins.pkgd.min.js to load the full-featured editor with all default plugins loaded.
  • Create a functional component called FroalaComponent that renders the Froala editor within a div.
  • Set the tag attribute of FroalaEditorComponent to textarea, this means the editor will be initialized at textarea HTML element.
  • (Optional) Set the config attribute of FroalaEditorComponent and pass your custom Froala options values through it. We will use it later to set up Filestack plugin options and events.

Step 4: Include Filestack For Uploading and Storing Files

To correctly display the Filestack File Picker and UI Transformation tools in the editor, include the following Filestack files:

We can directly add the script and link tags to your React project’s “public/index.html” file. This method ensures that the scripts are loaded with the initial HTML file.

However, for better performance, we will use the useEffect hook to dynamically add the scripts and stylesheet to the document when the component mounts and remove them when the component unmounts. This ensures the external resources are properly loaded and unloaded with the component lifecycle.

Here’s the “FroalaComponent.jsx” after including the Filestack scripts and stylesheet:

import React, { useEffect } from 'react';
import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/css/froala_editor.pkgd.min.css';
import FroalaEditorComponent from 'react-froala-wysiwyg';
import 'froala-editor/js/plugins.pkgd.min.js';

function FroalaComponent() {

    useEffect(() => {
        const filestackScript1 = document.createElement('script');
        filestackScript1.src = 'https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js';
        filestackScript1.async = true;
        document.body.appendChild(filestackScript1);

        const filestackScript2 = document.createElement('script');
        filestackScript2.src = 'https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js';
        filestackScript2.async = true;
        document.body.appendChild(filestackScript2);

        const filestackScript3 = document.createElement('script');
        filestackScript3.src = 'https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js';
        filestackScript3.async = true;
        document.body.appendChild(filestackScript3);

        const filestackStylesheet = document.createElement('link');
        filestackStylesheet.rel = 'stylesheet';
        filestackStylesheet.href = 'https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css';
        document.head.appendChild(filestackStylesheet);

        return () => {
            document.body.removeChild(filestackScript1);
            document.body.removeChild(filestackScript2);
            document.body.removeChild(filestackScript3);
            document.head.removeChild(filestackStylesheet);
        };
    }, []);

    return (
        <div className="editor">
            <h3>Froala's React WYSIWYG Editor</h3>
            <FroalaEditorComponent tag='textarea' />
        </div>
    );
}

export default FroalaComponent;

Step 5: Filestack Configuration

5.1: Create Filestack Account

In this step, we need to create a Filestack account and obtain a Filestack API key to add to the Froala configuration so we can upload files to your cloud storage through the Filestack File Picker. This powerful tool allows users to upload, store, and transform files directly. When integrated with Froala, it enables users to upload files from their local devices or cloud storage and apply various transformations within the Froala Editor interface.

You can create a free Filestack account with limited bandwidth, uploads, transformations, and storage, or start a free trial of a paid plan based on your needs.

create Filestack account

5.2: Set the Filestack Plugin Options

Login to your account and copy your Filestack API key.

Get Filestack API key

In the “FroalaComponent.jsx”, add a config parameter to FroalaEditorComponent where you can pass all the Froala configuration:

  • Set the filestackOptions.filestackAPI to your Filestack API key.
  • Set the filestackOptions.uploadToFilestackOnly to true. This will handle all file uploads by Filestack.
  • (Optional) If you want to customize the Filestack Picker, pass the File Picker configurations in the filestackOptions.pickerOptions option.
  • (Optional) Assign a callback function to the filestack.filestackPickerOpened event to perform a custom action after a user opens the Filestack File Picker.
  • (Optional) Assign a callback function to the filestack.filestackPickerClosed event to perform a custom action after a user closes the Filestack File Picker.
  • (Optional) Assign a callback function to the filestack.uploadedToFilestack event to perform a custom action when files are successfully uploaded to your cloud storage.
  • (Optional) Assign a callback function to the filestack.uploadFailedToFilestack event to perform a custom action if file upload fails.
import React, { useEffect } from 'react';
import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/css/froala_editor.pkgd.min.css';
import FroalaEditorComponent from 'react-froala-wysiwyg';
import 'froala-editor/js/plugins.pkgd.min.js';

function FroalaComponent() {
    let config = {
        filestackOptions: {
            uploadToFilestackOnly: true,
            filestackAPI: "***",
        },

        events: {
            'filestack.uploadedToFilestack': function (response) {
                console.log("Callback is triggered for uploaded to filestack ",)
            },

            'filestack.filestackPickerOpened': function (response) {
                console.log("Callback is triggered for picker opened ",)
            },

            'filestack.filestackPickerClosed': function (response) {
                console.log("Callback is triggered for picker closed ",)
            },

            'filestack.uploadFailedToFilestack': function (response) {
                console.log("Callback is triggered for file stack failed ",)
            },

        },
    };
    useEffect(() => {
        const filestackScript1 = document.createElement('script');
        filestackScript1.src = 'https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js';
        filestackScript1.async = true;
        document.body.appendChild(filestackScript1);

        const filestackScript2 = document.createElement('script');
        filestackScript2.src = 'https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js';
        filestackScript2.async = true;
        document.body.appendChild(filestackScript2);

        const filestackScript3 = document.createElement('script');
        filestackScript3.src = 'https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js';
        filestackScript3.async = true;
        document.body.appendChild(filestackScript3);

        const filestackStylesheet = document.createElement('link');
        filestackStylesheet.rel = 'stylesheet';
        filestackStylesheet.href = 'https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css';
        document.head.appendChild(filestackStylesheet);

        return () => {
            document.body.removeChild(filestackScript1);
            document.body.removeChild(filestackScript2);
            document.body.removeChild(filestackScript3);
            document.head.removeChild(filestackStylesheet);
        };
    }, []);

    return (
        <div className="editor">
            <h3>Froala's React WYSIWYG Editor</h3>
            <FroalaEditorComponent tag='textarea' config={config} />
        </div>
    );
}

export default FroalaComponent;

The “FroalaComponent.jsx” component can now be imported and used in other components of your React application.

5.3: Configure Cloud Storage

By default, all uploaded files are stored in Filestack’s internal S3 bucket. This doesn’t require any additional configuration and works for both free and paid Filestack accounts.

However, if you’re on a paid plan, you can store files in your custom cloud storage on the following platforms:

  • Amazon S3
  • Rackspace
  • Azure Blob Storage
  • Dropbox
  • Google Cloud Storage

Log in to your Filestack dev portal and follow the steps described here.

Step 6: Add Froala To Your Main Component

To display the Froala editor in your product, add the FroalaComponent to the template where you want the editor to be displayed.

In our tutorial, we will add it to the App.js file. It will be like

import './App.css';
import FroalaComponent from './components/FroalaComponent';

function App() {
  return (
    <div className="App">

      <FroalaComponent />
    </div>
  );
}

export default App;

 Step 7: Start Your Application

Open the terminal again and run the following command.

npm start

This will start the development server, which will display the Froala editor with Filestack buttons for uploading images, videos, and files.

Rich text-editor integrated with Filestack

Step 8: Test Your Application

You can test if your Filestack integration is working properly by following the below steps:

  • Upload images, videos, or files through Filestack File Picker.
  • Login to your Filestack dev portal.
  • Click on the “Content Browser“ and see if your files are listed.
  • Go to your cloud storage service and check if your file is successfully stored.

Conclusion

In this article, we’ve explored how to seamlessly integrate the Froala React Rich Text Editor with Filestack’s powerful file management capabilities within a React application. Filestack provides a user-friendly interface and a range of advanced image editing capabilities that can be easily integrated with the Froala editor.

The integration of Froala and Filestack streamlines the process of uploading, storing, and transforming files directly within the rich-text editor, empowering your users to focus on creating great content without the hassle of complex file management. With just a few simple steps, you can set up this integration and unlock advanced image editing tools, a user-friendly file picker, and a robust cloud storage solution.

So what are you waiting for? Try the Froala-Filestack integration and give your users the rich-text editing experience they deserve.

Get your Filestack API here for free.

 

Explore Froala Lists Plugin Setup, Options, and Methods

Froala Lists plugin

Crafting content with clear structure and organization is essential for effective communication. Fortunately, Froala – a powerful WYSIWYG HTML editor – offers advanced list formatting capabilities that go beyond the basic list features found in most editors. In this post, we’ll explore how you can harness Froala’s robust list management tools to create and customize lists like a pro.

What are HTML Lists? and How Are They Structured?

HTML lists are a way for web developers to group related items together in an organized manner. They help present content in a clear and structured way, making it more readable and accessible. There are three main types of lists in HTML:

  1. Ordered Lists (<ol>): These lists are used when the order of items matters. Each item is numbered.
  2. Unordered Lists (<ul>): These lists are used when the order of items doesn’t matter. Each item is marked with a bullet point.
  3. Definition Lists (<dl>): These lists are used for terms and their definitions.

Each type of list serves a specific purpose and can be customized to fit the design and content requirements of your website. Let’s break down how each type of list is structured:

Ordered List (<ol>):

<ol>

<li>First item</li>
<li>Second item</li>
<li>Third item</li>

</ol>
  • <ol>: This tag defines the start of an ordered list.
  • <li>: Each list item is wrapped in this tag.

Unordered List (<ul>):

 

<ul>

<li>First item</li>

<li>Second item</li>

<li>Third item</li>

</ul>
  • <ul>: This tag defines the start of an unordered list.
  • <li>: Each list item is wrapped in this tag.

Definition List (<dl>):

<dl>

<dt>Term 1</dt>

<dd>Definition of Term 1</dd>

<dt>Term 2</dt>

<dd>Definition of Term 2</dd>

</dl>
  • <dl>: This tag defines the start of a definition list.
  • <dt>: This tag is used for each term.
  • <dd>: This tag is used for each definition.

How does Froala Help in Creating HTML Lists?

Froala helps developers and non-developers create HTML content without needing to know or remember the HTML tags. Users can use the editor’s intuitive toolbar to format the content. The editor offers the option to create ordered or unordered lists without writing a single line of code. Moreover, Froala supports advanced list styling options, allowing users to customize the appearance of their lists. For example, you can change bullet points to different shapes. The Froala’s Lists plugin is responsible for providing this functionality.

By providing these features, Froala empowers non-developers to create well-structured and visually appealing HTML lists with ease, enhancing both the user experience and the quality of the web content.

Froala Lists plugin

Froala’s Lists plugin

Froala’s Lists plugin provides a comprehensive set of options and methods to create and manage HTML lists within your rich text editor. With Froala, you can easily insert, modify, and style unordered and ordered lists to enhance the structure and presentation of your content. The plugin allows you to seamlessly integrate lists into your web application’s content.

The Froala’s Lists plugin registers three buttons that can be added to the editor toolbar:

  1. formatOLSimple: Display a button for formatting content in an ordered list where list items will be numbered with numbers.
  2. formatOL: Display a list of options for formatting content in an ordered list
    1. Default: list items will be numbered with numbers.
    2. Lower Alpha: The list items will be numbered with lowercase letters style="list-style-type: lower-alpha;"
    3. Lower Greek: The list items will be numbered with lowercase classical Greek symbols style="list-style-type: lower-greek;"
    4. Lower Roman: The list items will be numbered with lowercase Roman numerals style="list-style-type: lower-roman;"
    5. Upper Alpha: The list items will be numbered with uppercase letters style="list-style-type: upper-alpha;"
    6. Upper Roman: The list items will be numbered with uppercase Roman numerals style="list-style-type: upper-roman;"
  3. formatUL: Display a list of options for formatting content in an unordered list
    1. Default: Sets the list item marker to a disc bullet (small black circle).
    2. Circle: Sets the list item marker to a hollow circle.
    3. Disc: Sets the list item marker to a small black circle.
    4. Square: Sets the list item marker to a filled square.

By default, the formatOL and formatUL are displayed in the “Paragraph” toolbar buttons group. Learn more about Froala’s toolbar configuration.

Formatting a List

To create a list:

  1. Click on one of the formatting toolbar buttons.
  2. Start typing to create the first list item.
  3. Press “Enter” to create a new list item.
  4. To create a second-level list item, press “Tab”.
  5. To decrease the list level, press “Shift + Tab”.
  6. When you’re finished with the list, press “Enter” twice to start a normal paragraph.

HTML lists

If the content was already on the editor

  1. Select it.
  2. Click on one of the formatting toolbar buttons and it will be converted to a list.

To reformatting a list:

  1. Select the list.
  2. Click on the same formatting toolbar button that was used to create the list.

Installation and Setup of Froala Lists Plugin

If you include the Froala packaged script, the Froala Lists plugin is active by default. However, if you only include the Froala core script, you will need to add the Lists plugin script separately.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lists</title>
    <!--Include Froala Stylesheet -->
    <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.min.css' rel='stylesheet'
        type='text/css' />

</head>

<body>

    <!--Editor element -->
    <textarea id="editor"></textarea>

    <!--Include Froala Script -->
    <script type='text/javascript'
        src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.min.js'></script>
            
    <!--Include Lists Plugin Script -->
    <script type='text/javascript'
        src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/plugins/lists.min.js'></script>


    <script>

        new FroalaEditor('#editor');
    </script>
</body>

</html>

If you are customizing the enabled plugins, add the “Lists” plugin to the `pluginsEnabled` option.

new FroalaEditor('#editor', {

  pluginsEnabled: ['lists', 'image', 'link', 'video']

});

When customizing the toolbar buttons, add the list formatting buttons you want to use to the toolbarButtons option.

new FroalaEditor('#editor', {

  pluginsEnabled: ['lists', 'image', 'link', 'video'],

  toolbarButtons: ['formatOL', 'formatUL', 'bold']

});

Similarly, customize the toolbarButtonsMD, toolbarButtonsSM, toolbarButtonsXS options. These options indicate the buttons to be displayed on medium, small, and extra small screens, respectively. By default, these options display the same buttons defined in the toolbarButtonsoption.

Customizing the Lists Plugin

Setting the listAdvancedTypes option to false disables the advanced types selection for the bullets. This restricts the list formatting options to the default settings only.

new FroalaEditor('#editor', {

  pluginsEnabled: ['lists', 'image', 'link', 'video'],

  toolbarButtons: ['formatOL', 'formatUL', 'bold'],

  listAdvancedTypes: false

});

Moreover, you can listen to the formatOL and formatUL actions and execute a custom function before or after them using Froala commands.before and commands.after events.

        new FroalaEditor('#editor', {
            pluginsEnabled: ['lists', 'image', 'link', 'video'],
            toolbarButtons: ['formatOL', 'formatUL', 'bold'],
            listAdvancedTypes: false,
            events: {
                'commands.before': function (cmd) {
                    if (cmd == 'formatUL' || cmd == 'formatOL') {
                        this.html.insert('Do somthing <b>before</b> ' + cmd + ' ');

                    }
                },
                'commands.after': function (cmd) {
                    if (cmd == 'formatUL' || cmd == 'formatOL') {
                        this.html.insert('Do somthing <b>after</b> ' + cmd + ' ');

                    }
                }
            }
        });

Additionally, the plugin provides a lists.format(tag_name) method, which allows developers to programmatically convert selected content into a list. If the tag_name is ‘OL’, the method will create an ordered list. If the tag_name is ‘UL’, the method will create an unordered list.

Try Froala List Plugin for Free

The Froala Lists plugin provides a flexible and customizable way to create and manage lists within your Froala-powered content editor. You can easily configure the available list formatting options, control the toolbar buttons, and even listen to list-related events to execute custom functionality. By leveraging the plugin’s programmatic methods, you can also dynamically convert content into ordered or unordered lists as needed. This level of control and extensibility allows you to tailor the list management experience to best fit your specific application requirements.

Ready to unlock the power of structured content? Try the Froala Editor for free today and experience the difference it can make in your web projects. Elevate your content with the advanced list formatting capabilities of Froala.

Seamlessly Integrate a Date Picker Into Froala Rich Text Editor

Integrate a date picker into Froala

Froala WYSIWYG editor is a powerful tool that transforms content management. Integrating a date picker into it enhances your whole application user experience. This can be easily achieved by incorporating a date picker JavaScript library into Froala.

This blog post will guide you through the process of integrating a date picker into the Froala Rich Text Editor using the MCDatepicker JavaScript library. You can use any other date picker alternative, the integration process will be almost the same.

MCDatepicker is a free, open-source date picker library with a clean design and flexibility, making it the ideal choice for managing dates with ease and accuracy. Join us as we delve into the step-by-step process of this integration, showcasing how you can enrich the Froala experience and streamline your content creation process with just a few lines of intuitive JavaScript.

Date picker integration into Froala rich text editor

Understanding the Role of a Date Picker in a Rich Text Editor

When it comes to rich text editors, usability and functionality are paramount. Adding a custom date picker enhances the user experience by providing an intuitive way to input dates. Using a JavaScript date picker simplifies the process, reducing user errors and improving the efficiency of content creation. Froala’s rich text editor is a great example of how we can integrate these tools seamlessly, offering developers a solution that’s both powerful and easy to use. Our focus on UX ensures that users have a smooth experience, and integrating a date picker is just one of the many ways we enhance the editor’s capabilities.

Why Should We Use Froala Rich Text Editor?

The Froala Rich Text Editor is a popular WYSIWYG (What You See Is What You Get) editor that provides a wide range of features and customization options.

It allows users to easily format text, and insert images, tables, and videos. It offers over 100 features. Check them all here.

One of the key benefits of the Froala Rich Text Editor is its extensibility, which enables developers to integrate additional functionality and features.

Setting Up MCDatepicker for Seamless Date Management

To manage dates effectively within Froala’s editor, we turn to MCDatepicker, a robust library renowned for its attractive design and ease of use. Setting up an MCDatepicker date picker allows us to handle date formats and calculations with precision. By leveraging MCDatepicker, developers can streamline date management, ensuring application consistency and reliability. The integration process is straightforward. Froala’s custom buttons approach makes it easy for developers to implement MCDatepicker within the editor.

Integrating the Date Picker

  1. Set up the Froala Rich Text Editor:
    1. Include the necessary Froala CSS and JavaScript files in your HTML file.
    2. Initialize the Froala Rich Text Editor on your desired HTML element.
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Insert date and time</title>
    <!--Include Froala Stylesheet -->
    <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet'
        type='text/css' />
    <!--Include Font awesome for the button icon -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"
        integrity="sha512-+L4yy6FRcDGbXJ9mPG8MT/3UCDzwR9gPeyFNMCtInsol++5m3bk2bXWKdZjvybmohrAsn3Ua5x8gfLnbE1YkOg=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>

<body>

    <!--Editor element -->
    <textarea id="editor"></textarea>

    <!--Include Froala javaScript -->
    <script type='text/javascript'

    <script>

        new FroalaEditor('#editor');
    </script>
</body>

</html>
  1. Install and include MCDatepicker:
    Download the MCDatepicker library or include it from a CDN.
<link href="https://cdn.jsdelivr.net/npm/mc-datepicker/dist/mc-calendar.min.css" rel="stylesheet" />

<script src="https://cdn.jsdelivr.net/npm/mc-datepicker/dist/mc-calendar.min.js"></script>
  1. Define a new Froala button and include the necessary functionality:
    As per the Froala custom button guide, we should:

    1. Define an icon for the custom button.
FroalaEditor.DefineIcon('calendar', { NAME: 'calendar', template: 'font_awesome' });
    1. Register the button
FroalaEditor.RegisterCommand('calendar', {
    1. Set a title
title: 'Display Calendar Popup',
    1. Specify the icon for the button. If this option is not specified, the button name is used.
icon: 'calendar',
    1. Save the button action into the undo stack.
undo: true,
    1. Set whether to focus inside the editor before the callback or not
focus: false,
    1. Set a callback function to be called when the button is hit.
    callback: function () {
        const datepicker = MCDatepicker.create();
        datepicker.open();
        datepicker.onSelect((date, formatedDate) => {
            this.html.insert('Selected date: ' + formatedDate);
        });
}

In the callback function, we used the MCDatepicker.create() method to initialize the date picker and then automatically display the picker using the datepicker.open(); method.
When the user selects a date and clicks on the “OK“ button, the selected date is inserted in the editor. We achieved this using the MCDatepicker onSelect event. This event provides the selected date and formatted date. We then used the html.insert() Froala method to insert the formatted date into the Froala editor.
The MCDatepicker provides the formatted date based on the format specified with the dateFormat option, which is set to DD-MMM-YYYY by default. By customizing the dateFormat option, you can customize the date format to suit your specific needs. Once the date picker is integrated, users can easily select dates within the Froala Rich Text Editor, streamlining the content creation process.

rich text editor

  1. Display the date picker button on the Froala toolbar
    Add the newly created custom button to Froala’s toolbarButtons options. Master the customization of Froala toolbar buttons.
        new FroalaEditor('#editor', {
            // Add the custom buttons in the toolbarButtons list, after the separator.
            toolbarButtons: [['calendar', 'italic', 'bold']]
        });
  1. The final code
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Insert date and time</title>
    <!--Include Froala Stylesheet -->
    <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet'
        type='text/css' />
    <link href="https://cdn.jsdelivr.net/npm/mc-datepicker/dist/mc-calendar.min.css" rel="stylesheet" />
    <!--Include Font awesome for the button icon -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"
        integrity="sha512-+L4yy6FRcDGbXJ9mPG8MT/3UCDzwR9gPeyFNMCtInsol++5m3bk2bXWKdZjvybmohrAsn3Ua5x8gfLnbE1YkOg=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>

<body>

    <!--Editor element -->
    <textarea id="editor"></textarea>

    <!--Include Froala javaScript -->
    <script type='text/javascript'
        src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>
    <script src="https://cdn.jsdelivr.net/npm/mc-datepicker/dist/mc-calendar.min.js"></script>
    <script>
        // Define an icon and command for the button that opens the custom popup.
        FroalaEditor.DefineIcon('calendar', { NAME: 'calendar', template: 'font_awesome' });
        FroalaEditor.RegisterCommand('calendar', {
            title: 'Display Calendar Popup',
            icon: 'calendar',
            undo: true,
            focus: false,
            popup: false,

            callback: function () {
                const datepicker = MCDatepicker.create();
                datepicker.open();
                datepicker.onSelect((date, formatedDate) => {
                    this.html.insert('Selected date: ' + formatedDate);
                });

            }
        });
    </script>
    <script>

        new FroalaEditor('#editor', {
            // Add the custom buttons in the toolbarButtons list, after the separator.
            toolbarButtons: [['calendar', 'italic', 'bold']]
        });
    </script>
</body>

</html>

Customize The Date Picker

The MCDatepicker library offers a range of customization options, enabling developers to tailor the date picker’s appearance and behavior to match the branding and design of their application. By leveraging these features, you can create a cohesive and visually appealing date management solution within the Froala Rich Text Editor. For example, you can disable some weekdays, specify allowed years, or change the date picker theme.

Conclusion

Integrating a date picker into the Froala Rich Text Editor using MCDatepicker can be a powerful way to enhance the user experience and improve the overall quality of your web content. By following the steps outlined in this blog post, you can seamlessly incorporate this functionality into your web application or website.

This seamless integration of MCDatepicker enhances the overall functionality and user experience of the Froala editor, making it a powerful tool for developers to create rich and engaging content. The flexibility to add custom features like the date picker sets Froala apart as a versatile and extensible rich text editing solution.

If you’re looking to enhance your web application’s content creation experience, I encourage you to give Froala a try. With its robust API, extensive feature set, and easy integration, Froala makes it simple to build a WYSIWYG editor that is perfectly suited to your users’ needs.

Using JavaScript Date Object to Add Date/Time in a JavaScript WYSIWYG Editor

JavaScript WYSIWYG Editor

The JavaScript Date object is a powerful tool that allows developers to work with dates and times in their web applications. JavaScript WYSIWYG editors can utilize it to allow users to insert specific dates and times in their content. In this blog post, we’ll explore using the Date object to insert date and time into the Froala WYSIWYG editor.

Understanding the Date Object

The Date object in JavaScript represents a single moment in time. It provides a variety of methods for working with dates and times, such as getting the current date and time, formatting dates, and performing date calculations.

The Date object can be created in several ways, including using the new Date() constructor or by passing specific date and time values to the constructor.

Displaying the Current Date

Getting the Current Date

To get the current date, you can use the new Date() constructor without any arguments. This will create a new Date object representing the current date and time.

const currentDate = new Date();

Formatting the Date

Once you have the current date, you can use various methods of the Date object to format the date in the desired way. We want to display the inserted date and time in the following format Month/Day/Year Hours:Minutes:Seconds. The methods we will use in our case are:

  • getFullYear(): Returns the year as a four-digit number (e.g., 2023)
  • getMonth(): Returns the month as a zero-based number (0 for January, 1 for February, etc.)
  • getDate(): Returns the day of the month (1-31)
  • getDay(): Returns the day of the week as a zero-based number (0 for Sunday, 1 for Monday, etc.)
  • getHours(): Returns the hours (0-23)
  • getMinutes(): Returns the minutes (0-59)
  • getSeconds(): Returns the seconds (0-59)

If you want another format, you can check the Date JavaScript documentation for other methods.

Displaying the Date

After getting the current date and formatting it, you can display the date on your web page.

You can use JavaScript to update the content of an HTML element, such as a <p> or <div> tag, with the formatted date.

const currentDate = new Date();

const dateString = `Current date and time is ${currentDate.getMonth() + 1}/${currentDate.getDate()}/${currentDate.getFullYear()} ${currentDate.getHours()}:${currentDate.getMinutes()}:${currentDate.getSeconds()}`;

document.getElementById('date-display').textContent = dateString;

In this example, we create a new Date object, format the date using the methods mentioned above, and then update the text content of an HTML element with the ID `date-display`.

Now let’s use it with Froala WYSIWYG editor but first let’s explain what WYSIWYG editor means, why we want to insert the current date in it, and how to do it.

What are WYSIWYG Editors?

WYSIWYG (What You See Is What You Get) editors are text editors that allow users to format and style content as they type, without having to write raw HTML or markup. These editors provide a user-friendly interface, making it easier for non-technical users to create and edit web content.

datetime with Froala

Why Do I Need To Insert The Current Date While Using WYSIWYG Editor?

WYSIWYG Editors are used in many use cases where adding current date and time are important to users. For example:

  • In Content Management Systems (CMSs): users can insert the current date when creating a new blog post or article. This helps provide context and timestamp the content.
  • In Email Clients: users may want to insert the current date when composing a new email message.
  • In Online Forms: users may need to insert the current date when filling out forms, such as job applications or registration forms.
  • In Note-taking Apps: users may want to timestamp their notes with the current date.

By utilizing the JavaScript Date object, developers can enable users to insert the current date and time directly into the content they are creating or editing, enhancing the functionality and convenience of the WYSIWYG editor.

Why It’s Recommended to Use Froala Editor?

Froala Editor is an advanced WYSIWYG editor with a user-friendly interface. It offers a wide range of features and tools, including advanced formatting options, image and media integration, and export to PDF, allowing users to create high-quality content efficiently.

One of the most important features is its powerful API that allows developers to easily and quickly customize the editor to fit the specific needs and branding of your organization, allowing you to create a unique and tailored content creation experience.

How To Insert Date and Time Into Froala JavaScript WYSIWYG Editor?

First, we need to add a new toolbar button. When this button is clicked, it inserts the current date and time into the editor. Froala made defining new toolbar buttons easy. You just need to follow this “create a custom Froala button“ guide.

The main steps to define a custom button and display it in the editor toolbar are:

  • Define the button icon to be displayed on the editor toolbar
  • Define the button’s action, which in our case will be to insert the current date and time into the editor.
  • Register the custom button with Froala’s API

Define button icon

We will use the calendar icon from the Font Awesome library.

FroalaEditor.DefineIcon('dateIcon', {NAME: 'calendar', template: 'font_awesome'})

Define the button’s action

Here is the button definition and inside the callback function we will use the JavaScript Date object as we used earlier to format the current date and time and then we will use the html.set() Froala Method to insert the date and the time into the editor.

        FroalaEditor.RegisterCommand('date', {
            title: "Today's date and time",
            icon: 'dateIcon',
            undo: true,
            focus: true,
            showOnMobile: true,
            refreshAfterCallback: true,
            callback: function () {

                const currentDate = new Date();
                const dateString = `${currentDate.getMonth() + 1}/${currentDate.getDate()}/${currentDate.getFullYear()} ${currentDate.getHours()}:${currentDate.getMinutes()}:${currentDate.getSeconds()}`;

                this.html.set("<i>"+dateString+"</i>");
            },

        })

Register the custom button with Froala’s API

In a basic HTML project, initialize the editor and the date custom button we created above to Froala’s toolbarButtons option.

Here’s the full code example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Insert date and time</title>
    <!--Include Froala Stylesheet -->
    <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />
    <!--Include Font awesome for the button icon -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css" integrity="sha512-+L4yy6FRcDGbXJ9mPG8MT/3UCDzwR9gPeyFNMCtInsol++5m3bk2bXWKdZjvybmohrAsn3Ua5x8gfLnbE1YkOg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>

    <!--Editor element -->
    <textarea id="editor"></textarea>

    <!--Include Froala javaScript -->
    <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>
    <script>
        FroalaEditor.DefineIcon('dateIcon', {NAME: 'calendar', template: 'font_awesome'})
        FroalaEditor.RegisterCommand('date', {
            title: "Today's date and time",
            icon: 'dateIcon',
            undo: true,
            focus: true,
            showOnMobile: true,
            refreshAfterCallback: true,
            callback: function () {

                const currentDate = new Date();
                const dateString = `${currentDate.getMonth() + 1}/${currentDate.getDate()}/${currentDate.getFullYear()} ${currentDate.getHours()}:${currentDate.getMinutes()}:${currentDate.getSeconds()}`;

                this.html.set("<i>"+dateString+"</i>");
            },

        })

        new FroalaEditor('#editor', {
            // Add the custom buttons in the toolbarButtons list, after the separator.
            toolbarButtons: [['date', 'italic' , 'bold']]
        });
    </script>
</body>
</html>

By following these steps, you can easily integrate the ability to insert the current date and time into your Froala-powered web applications, providing users with a convenient way to timestamp their content.

Advanced Date Formatting

While the basic formatting methods provided by the Date object are useful, you may sometimes need more advanced date formatting options. In that case, it’s recommended to integrate third-party libraries, such as Moment.js with Froala editor to provide additional date formatting capabilities.

These libraries offer a wide range of formatting options, including the ability to display dates in different languages, time zones, and custom formats.

If you recommend writing an article about how to do that integration, leave a comment below.

Try Froala for Your Next Project

In this article, we’ve explored how to leverage the powerful JavaScript Date object to insert the current date and time into a Froala WYSIWYG editor. By creating a custom toolbar button, we were able to give users a convenient way to timestamp their content directly within the editor interface.

The ability to seamlessly integrate date and time functionality into a WYSIWYG editor can be a valuable feature for a wide range of applications, from content management systems to online forms and note-taking apps. With the flexibility and customization options provided by Froala, developers can tailor this functionality to perfectly fit the needs of their users and their application’s branding.

If you’re looking to enhance your web application’s content creation experience, I encourage you to give Froala a try. With its robust API, extensive feature set, and easy integration, Froala makes it simple to build a WYSIWYG editor that is perfectly suited to your users’ needs.

Get started with Froala today and unlock the power of dynamic date and time integration in your web applications!

Customizing Froala’s Behavior with Command-Driven Events

Froala commands API

Froala is a powerful WYSIWYG editor created by developers for developers. Its robust API empowers users to create highly customized and seamless user experiences. One of the Froala API’s standout features is the ability to execute commands programmatically. Furthermore, developers can run custom functions before or after specific commands are triggered.

In this blog post, we’ll explore the steps to master programmatic command execution and learn how to listen for their related events in Froala. By the end, you’ll have a solid understanding of how to leverage Froala’s advanced API Commands methods and events to build exceptional content editing experiences.

What Are the Types of Commands I Can Execute Programmatically In Froala

There are several types of commands that developers can call in their custom code. Here is the complete list:

  1. Format The Selected Text
    1. Bold
      Developers can use the commands.bold() method to format the user-selected text as bold.
    2. Italic
      Developers can use the commands.italic() method to format the user-selected text as italic.
    3. strikeThrough
      The commands.strikeThrough() method helps developers to format the user-selected text as a strikethrough.
    4. Subscript
      The commands.subscript() method helps developers format the user-selected text as a subscript.
    5. Superscript
      The commands.superscript() method helps developers format the user-selected text as a superscript.
    6. Underline
      The commands.underline() method helps developers format the user-selected text as an underlined.
    7. Indent
      Using the commands.indent() method, developers can indent more of the selected paragraphs.
    8. Outdent
      Using the commands.outdent() method, developers can indent fewer of the selected paragraphs.
  2. Clear Formatting
    If a developer wants to clear the format applied to the selected text, he can execute the commands.clearFormatting() method.
  3. Insert a horizontal line
    The commands.insertHR() method helps developers insert a horizontal line in the editor.
  4. Redo
    Using the commands.redo() method, developers can redo the user’s most recent action.
  5. Undo
    Using the commands.undo() method, developers can undo the user’s last executed action.
  6. Select All
    Using the commands.selectAll() method, developers can select all the content inside the editor.
  7. Toolbar
    1. Display The Inline Toolbar
      The commands.show() method displays the inline toolbar at the cursor position.
    2. Open sub-toolbars
      1. The commands.moreText() method opens the more text actions toolbar.
      2. The commands.moreParagraph() method opens the more paragraph actions toolbar.
      3. The commands.moreRich() method opens the more rich text actions.
      4. The commands.moreMisc() method opens the more miscellaneous actions toolbar.
      5. The commands.moreTrackChanges() method opens the track changes actions toolbar.

All the methods do not accept any arguments, and you can call them from the editor instance. For example, to call the moreText command, you can do it like this

var editor = new FroalaEditor('.selector', {}, function () {

  // Call the method inside the initialized event.

  editor.commands.moreText ();

})

In the above code, the commands.moreText() method is called once the editor is initialized. This opens the “More Text” actions toolbar.

Customize The Editor Based on The Executed Commands

The Froala API provides developers with over 100 events that can be used to listen for specific actions performed by the user. Five of these events allow developers to customize the editor’s behavior and appearance based on the executed commands. By leveraging these events, developers can create highly interactive experiences tailored to their users’ needs. Let’s dig deeper into these events.

Execute Actions Prior to Command Execution

The commands.before event is triggered right before a command is executed. This allows developers to perform custom actions or validations before the command is carried out. For example, developers can use this event to display a confirmation dialog, update the UI, or perform any other action.

The command name is passed as the first parameter of the callback function for the commands.before event. To see the full list of commands that trigger this event, refer to the documentation. Depending on the command type, a second parameter may be defined in the callback function, providing information related to the executed command. For example, when the fontSize command is executed, the second parameter will be the selected font size.

Developers can listen to the commands.before event, check which command is being executed, and then take an appropriate action based on that command. For example:

var editor = new FroalaEditor('.selector', {
  events: {
    'commands.before': function (command, param) {
      // Perform custom actions here.
      console.log('Command about to be executed:', command);
      if(command== "fontSize"){
        if(param == "72px")
            this.inlineStyle.apply('color: red;');
      }      
    }
  }
});

In the above example, the `commands.before` event is used to listen for commands before they are executed. In this case, when the fontSize command is about to be executed, the code checks if the selected font size is 72px. If so, it applies a custom inline style to the editor, setting the text color to red. This shows how developers can customize the editor’s behavior based on the specific command being executed.

In the code, we used the inlineStyle.apply method to style the text. Click to learn more about the Froala Inline Style plugin and how it differs from the Inline Class plugin.

Execute Actions Following Command Execution

If you need to run custom code after a specific command is executed, you can use the commands.after event. This event is triggered immediately after a command is executed, allowing you to perform additional actions or update the UI as needed. The callback function for this event receives the same parameters as the commands.before event – the command name and any additional information related to the executed command.

Execute Actions According to the Clicked Button

Froala offers the commands.mousedown(btn) event which is triggered when a button in the editor’s toolbar is clicked. This allows developers to perform custom actions based on the specific button that was clicked. The callback function for this event receives the clicked button element as a parameter, which can be used to identify the button and execute the desired logic.

In the following example, the commands.mousedown event is used to listen for when a button in the editor’s toolbar is clicked. In this case, when the “Bold” button is clicked, the code checks the data-cmd attribute of the clicked button to identify the command. If the command is “bold”, it applies a custom inline style to the editor, setting the text color to red. This demonstrates how developers can customize the editor’s behavior based on the specific button that was clicked.

let editor = new FroalaEditor('#editor', {

        events: {

            'commands.mousedown': function(btn) {
                  // Do something here.
                  // this is the editor instance.
                  let cmd = btn[0].getAttribute('data-cmd');
                  if( cmd == "bold"){
              this.inlineStyle.apply('color: red;');
                  }
  
           }
        }
    }, function () {

});

The Difference Between Before, After, and Mousedown Command Events

Here are the key differences between these events to help you choose the right one:

  • The Mousedown event is triggered before the Before and After events.
  • The Mousedown event can be triggered by any toolbar button, while the Before and After events are specific to certain commands.
  • The callback function for Before and After events may include a second parameter with additional information about the executed command.

Redo and Undo Specific Command Events

The Froala API also provides events for handling redo and undo actions. The commands.redo() event is triggered when the user performs a redo action, while the commands.undo()event is triggered when the user performs an undo action. These events allow developers to customize the editor’s behavior or update the UI in response to these actions.

For example, you could use the commands.redo event to update a counter or button state to reflect the current redo/undo state. Similarly, the commands.undo event could be used to update the UI to show that an action has been undone. By leveraging these events, developers can create a more responsive and interactive editor’s behavior.

Elevate Your Application User Experience

Froala’s powerful API and rich set of events provide developers with the tools to create highly customized and interactive content editing experiences. By leveraging the commands.before, commands.after, and commands.mousedown events, you can execute custom logic at key points in the editing workflow – before and after commands are executed, and when specific toolbar buttons are clicked.

These events, combined with the ability to inspect the executed commands and their parameters, give you granular control over Froala’s behavior. You can use this to display confirmations, update the UI, apply custom styles, and much more. The redo and undo-specific events also allow you to keep your application in sync with the user’s actions.

With this knowledge, you’re now equipped to take your Froala-powered applications to new heights. Start experimenting with command-driven events today and unlock the full potential of this robust WYSIWYG editor. Download Froala for free and try it out for yourself!

Inline Styles vs Classes: Best Practices for Froala-Powered Apps

inline styles and inline classes

Styling text is essential for modern web applications. Rich-text editors make it easy to style text and preview changes in real time. These editors provide various buttons to apply different styles to the text. Professional WYSIWYG editors, like Froala, go a step further. They allow developers to combine multiple formats for the end-user to apply with a single button, streamlining the process of applying styles. This helps create a consistent user experience for the end-user.

The Froala inline styles and inline classes plugins help in styling text but using two different approaches. Each approach has its advantages and disadvantages, and the choice between them depends on the project’s specific requirements. Inline styles are applied directly to the HTML element, while inline classes are applied to the element using a CSS class. The choice between the two depends on factors such as the complexity of the styling, the need for reusability, and the overall maintainability of the codebase.

In this article, we will explore the difference between inline styles and inline classes plugins, and provide guidance on when to use each approach. Understanding the differences between these two plugins can help developers make informed decisions and create more efficient and maintainable web applications.

Froala inline class and inline styles plugins

How Does The Froala Inline Style Plugin Work?

The Froala Inline Style plugin offers the inlineStyles option that is used to define some CSS styles that can be applied to text.

When the Froala Inline Style plugin is activated, a button appears on the editor toolbar that opens a list of the predefined styles. Choosing a style will apply its corresponding CSS rules inline to the selected text allowing end-users to effortlessly enhance the visual appeal of your text.

How Does The Froala Inline Class Plugin Work?

The Froala Inline Class plugin offers the inlineClasses option that is used to define some CSS class names that can be applied to text. The CSS classes themselves should be defined in the page stylesheet.

When the Froala Inline Class plugin is activated, a button appears on the editor toolbar that opens a list of the predefined styles. Choosing a style will apply its corresponding CSS class to the selected text allowing end-users to effortlessly enhance the visual appeal of your text.

Inline Style VS Inline Class

Both plugins offer a user-friendly way to make your text more engaging and visually appealing, helping you stand out with iconic text styles.

The choice between inline styles and inline classes often depends on the specific requirements of the project, such as the complexity of the styling, the need for reusability, and the overall maintainability of the codebase.

Inline styles are useful for simple, one-off styling requirements, as they can be quickly applied and don’t require additional CSS files. However, they can make the HTML code more cluttered and harder to maintain. Inline classes, on the other hand, allow for more modular and reusable styling, as the CSS can be defined in a separate file. This can lead to a more organized and maintainable codebase but may require more upfront effort to set up.

Developers should consider factors such as code maintainability, performance, and overall project requirements when deciding which approach to use. Ultimately, a combination of both techniques may be the most effective solution, allowing for flexibility and consistency in the application’s styling.

What is the difference between Inline Style, Inline Class, and Paragraph Style Plugin?

The Paragraph Style plugin in Froala is a separate plugin that allows users to apply predefined styles to entire paragraphs, rather than just inline text. In contrast, the Inline Style and Inline Class plugins focus on applying styles to selected text within a paragraph. The choice between these plugins depends on the specific needs of the project and the desired level of control over the text formatting.

Learn more about the Paragraph Style plugin.

The Inline Style and Inline Class Plugins in Code

Both plugins are included by default when the Froala packaged JavaScript file is included. However, if you’re using the core editor files only, you may include the plugins individually.

Installation

Use the following code to include the Inline Style plugin:

<script type='text/javascript' src='{url_based_on_your_download_option}/js/plugins/inline_style.min.js'></script>

Use the following code to include the Inline Class plugin:

<script type='text/javascript' src='{url_based_on_your_download_option}/js/plugins/inline_class.min.js'></script>

Activation

When customizing the enabled plugins, ensure that the inlineStyle and inlineClass values are included in the pluginsEnabled array to keep the Inline Style and Inline Class plugins enabled.

new FroalaEditor('#HTMLElement',{

   pluginsEnabled: ['image', 'link', 'video', 'inlineStyle', 'inlineClass']

});

When customizing the editor toolbar buttons, ensure that the inlineStyle and inlineClass values are included in the toolbarButtons array to display the buttons needed to open the dropdown corresponding to each plugin.

new FroalaEditor('#HTMLElement',{

    toolbarButtons: ['inlineStyle', 'inlineClass', 'bold', 'italic', 'underline', 'fontFamily', 'fontSize', '|', 'paragraphFormat', 'align', 'undo', 'redo', 'html'],

});

Styles Definition

For Inline Styles, define styles using inlineStyles option. It is an object where the property name is the text shown in the dropdown menu when the inlineStyle button is clicked while the property’s value is the inline CSS rules that will be applied to the text. For example, if the inlineStyles is

// Define new inline styles.

inlineStyles: {

      'Big Red': 'font-size: 20px; color: red;',

      'Small Blue': 'font-size: 14px; color: blue;'

}

This will display two options on the dropdown menu:

  • Big Red: once selected, the editor will wrap the selected text into <span style=”font-size: 20px; color: red;”> </span>.
  • Small Blue: once selected, the editor will wrap the selected text into <span style=”font-size: 14px; color: blue;”> </span>.

For Inline Classes, define styles using inlineClasses option. It is an object where the property name represents a CSS class and its corresponding value is the text shown in the dropdown menu when the inlineClasses button is clicked. For example, if the assigned object is

// Define new inline styles.

inlineClasses: {

   'fr-class-code': 'Code',

   'fr-class-highlighted': 'Highlighted',

   'fr-class-transparency': 'Transparent'

}

and define the classes in the CSS code

<style>

  .fr-view .fr-class-highlighted {

    background-color: #ffff00;

  }

  .fr-view .fr-class-code {

    border-color: #cccccc;

    border-radius: 2px;

    -moz-border-radius: 2px;

    -webkit-border-radius: 2px;

    -moz-background-clip: padding;

    -webkit-background-clip: padding-box;

    background-clip: padding-box;

    background: #f5f5f5;

    padding: 10px;

    font-family: "Courier New", Courier, monospace;

  }

  .fr-view .fr-class-transparency {

    opacity: 0.5;

  }

</style>

This will display three options on the  Inline Classes dropdown menu:

  • Code: when selected, the editor will toggle the ‘fr-class-code’ class in the selected text.
  • fr-class-code: when selected, the editor will toggle the ‘fr-class-highlighted’ class in the selected text.
  • fr-class-code: when selected, the editor will toggle the ‘fr-class-transparency’ class in the selected text.

Plugins Methods

The Inline Styles plugin provides the inlineStyle.apply(value) method, which can be used to dynamically apply inline styles to a text. The value parameter is a string that represents the inline CSS style to be applied to the selected text.

The Inline Class plugin provides the inlineClass.apply(value) method, which can be used to dynamically add a specific class to the selected text. The value parameter is the name of the defined class that should be applied to the selected text.

Full Code Example

Here is a full code example:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0" />
        <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />

        <style>

          .fr-view .fr-class-highlighted {
            background-color: #ffff00;
          }
        
          .fr-view .fr-class-code {
            border-color: #cccccc;
            border-radius: 2px;
            -moz-border-radius: 2px;
            -webkit-border-radius: 2px;
            -moz-background-clip: padding;
            -webkit-background-clip: padding-box;
            background-clip: padding-box;
            background: #f5f5f5;
            padding: 10px;
            font-family: "Courier New", Courier, monospace;
          }
        
          .fr-view .fr-class-transparency {
            opacity: 0.5;
          }

        </style>
    </head>

    <body>

            <textarea id="editor"></textarea>


        <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>

        <script> 
            new FroalaEditor('div#froala-editor', {
              toolbarButtons: ['inlineStyle', 'inlineClass', 'bold', 'italic', 'underline', 'strikeThrough', 'fontFamily', 'fontSize', '|', 'align', 'undo', 'redo', 'html'],
            
              // Define new inline styles.
              inlineStyles: {
                'Big Red': 'font-size: 20px; color: red;',
                'Small Blue': 'font-size: 14px; color: blue;'
              },
                  inlineClasses: {
                  'fr-class-code': 'Code',
                  'fr-class-highlighted': 'Highlighted',
                  'fr-class-transparency': 'Transparent'
                },
              events: {
                'commands.after': function(cmd) {
                  // Do something here.
                  // this is the editor instance.
                  if(cmd== "strikeThrough"){
                   this.inlineStyle.apply('font-size: 20px; color: red;');
\                  
                  }
                        // this is the editor instance.
                  if(cmd== "bold"){
                   this.inlineClass.apply('fr-class-code');
                  }
                }
              }
            })

        </script>
    </body>

</html>

Balancing Simplicity and Maintainability in Froala’s Rich-Text Editor

Froala, a popular rich-text editor, offers two approaches to enhancing the visual appeal of text in web applications: inline styles and inline classes. Both are powerful tools, but each has its own advantages and disadvantages.

Inline styles, as offered by Froala’s Inline Style plugin, provide a quick and easy way to apply formatting to text. With just a few clicks, you can wrap your selected text in custom CSS rules, making it stand out and grab your users’ attention. This can be particularly useful for simple, one-off styling requirements.

However, inline styles can also lead to cluttered HTML and maintainability issues over time. That’s where Froala’s Inline Class plugin comes in. This approach allows you to define CSS classes in your stylesheet and then easily apply them to text within the editor. While it may require a bit more upfront effort to set up, this modular and reusable approach can result in a cleaner, more organized codebase.

As you continue to build and enhance your web applications, I encourage you to download Froala and experiment with both the Inline Style and Inline Class plugins. Take the time to carefully consider the tradeoffs between the two approaches and choose the one that best fits your specific needs. With Froala’s powerful tools and the right techniques, you can create engaging and visually appealing content that captivates your users and helps your application stand out from the crowd.
Download Froala Editor

Classic, IFrame, Inline & Document Modes: HTML Editor Software Differences

popular rich text editor

Froala is a popular rich text editor that offers users various editing modes, each with its own user interface and use cases. As a writer or content creator, understanding the differences between these modes can help you select the most appropriate one for your project needs.

In this blog post, we’ll take a deep dive into the four main editing modes provided by Froala: Classic, IFrame, Inline, and Document. We’ll explore the key characteristics of each mode, their benefits, and the scenarios where they are best suited. By the end, you’ll have a solid understanding of Froala’s editing capabilities and be equipped to choose the right mode for your content creation workflows.

Froala editor modes

Classic Froala Editor

basic mode

The Classic mode is the default and most commonly used editing mode in Froala. In this mode, the editor is displayed as a standalone element on the page, typically within a <div> or <textarea> element.

This mode is the default mode in the Froala editor. You don’t need any special configuration when you initialize the editor.

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0" />
        <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.min.css' rel='stylesheet' type='text/css' />
    </head>

    <body>

        <div id="froala-editor"></div>

        <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.min.js'></script>
        <script> 

         new FroalaEditor('div#froala-editor');

        </script>
    </body>

</html>

In this mode, the editor toolbar is always visible at the top of the editor. If you want to make the toolbar stay visible as you scroll the content, you need to enable the toolbarSticky option.

 new FroalaEditor('div#froala-editor', {
    toolbarSticky: true
  })

You can also display the toolbar at the bottom instead of the top of the editor by setting the toolbarBottom option to true.

new FroalaEditor('div#froala-editor', {

    toolbarBottom: true

  })

Explore how to customize the Froala editor toolbar.

The Froala classic mode is suitable for scenarios where you want the editor to be a distinct element on the page, such as in a content management system or a form. It provides a familiar and intuitive interface for users to input and format text.

IFrame Froala Editor

The IFrame mode embeds the Froala editor within an <iframe> element. This isolates the editor’s content and styling from the main page, providing a more secure and independent editing environment.

This mode is useful when you need to ensure the editor’s content and styles do not interfere with the surrounding page. It can be particularly helpful in scenarios where the page has complex layouts or existing styles that could potentially conflict with the editor.

The user interface of the editor is the same as it is in the classic mode.

To enable this mode, set the iframe option to true.

new FroalaEditor('div#froala-editor', {

iframe: true

})

Full Page Mode

The Full Page mode is similar to the classic mode but allows the usage of HTML, HEAD, BODY tags and DOCTYPE declaration. This mode is useful when you need to edit the entire web page, including the <head> and <body> sections. It provides a more comprehensive editing experience, allowing you to modify the page’s metadata, styles, and overall structure. The Full Page mode is particularly beneficial when working on standalone HTML pages or templates that require a complete document-level editing capability.

To enable the Full Page mode, set the fullPage option to true when initializing the Froala Editor.

new FroalaEditor('div#froala-editor', {
   fullPage: true
 })

Inline (Distraction-Free) Mode

inline mode

The minimalist interface of this mode helps you focus on your content. In Froala’s Inline mode, the editor’s toolbar remains accessible but stays hidden until needed, providing a clean and minimalist interface, ensuring a seamless and uninterrupted writing experience. This mode makes it easier for users to focus on their content.

var editor = new FroalaEditor('div#froala-editor',{

toolbarInline: true,

});

The toolbarVisibleWithoutSelection option allows you to control whether the toolbar should be displayed when the user:

  1. Select content within the editor.
  2. Focuses on the editor without selecting any content.

This gives you the flexibility to decide when the toolbar should be visible to the user.

var editor = new FroalaEditor('div#froala-editor',{

toolbarInline: true,

toolbarVisibleWithoutSelection: true,

});

By default, Froala displays Character and Word Counts at the bottom of the editing area. However, it may be feasible to hide this information in this mode.

var editor = new FroalaEditor('div#froala-editor',{

toolbarInline: true,

toolbarVisibleWithoutSelection: true,

charCounterCount: false,

wordCounterCount: false

});

This mode is suitable for scenarios where you want to provide a seamless editing experience within the page’s content, such as in a blog post or a content-heavy website.

Explore Froala’s inline editing mode.

Document Mode

document mode

The Document mode in Froala is similar to the classic mode but with a different default toolbar configuration optimized for creating online documents. The editing area is taller, providing an A4 page layout design. However, this mode does not offer page break, headers, or footers features. The Document mode is best suited for scenarios where you need a rich text editor with a document-like appearance, such as in a word processor or a report generator. The increased editing area height makes it easier to work with longer-form content.

The content is editable within the editor, and the changes are reflected in the underlying HTML structure.

To enable this mode, set the documentReady option to true.

new FroalaEditor('div#froala-editor',{

documentReady : true,

});

Edit in Popup

popup mode

The Froala editor’s “Edit in Popup” mode allows users to quickly update text content within a focused popup environment. In this mode, the toolbar functionality is not available, making formatting a text is not an option but users can easily make simple text updates without the complexity of the complete editor interface. To enable this mode, set the editInPopup option to true when initializing the Froala editor. The popup will appear when the user focuses on the text, providing a streamlined experience for updating specific content areas within your application.

new FroalaEditor('div#froala-editor',{

editInPopup : true,

});

What Are Froala Initialize Modes?

Froala is a flexible editor that can be initialized on different HTML elements, giving different UI and options for each.

The different modes we have discussed in this article can be applied when the editor is initialized on <div>, <p>, or <textarea> elements. However, the Froala editor can be initialized on other elements where these modes will not be applicable. For example:

  • Initialize on a Button: in this mode, a popup will be displayed to update the button text.
  • Initialize on an Image: The image popup will be displayed to replace or edit the image.
  • Initialize on a link: allowing you to update, remove, and set link attributes.

Conclusion

Froala rich text editor offers a variety of editing modes to cater to different use cases. The choice of editing mode will depend on the specific requirements of your project and the type of editing experience you want to provide to your users. By understanding the differences between the Classic, IFrame, Inline, and Document modes, you can choose the most appropriate mode for your project and provide a seamless and efficient editing experience for your users.

Try Froala for free and explore its different modes.

Unlock the Power of Customizable Toolbars with Froala

Froala Customizable Toolbars

As a content creator, you know that a rich text editor is only as powerful as its customization capabilities. That’s why Froala stands out – it offers a flexible, modular architecture that lets you tailor the editor’s functionality and design to fit your unique needs.

The toolbar is a prime example. With Froala, you can position it at the top or bottom, and display it in a classic view or an inline layout. But the magic happens when you optimize the toolbar for different screen sizes, creating a truly responsive editing experience.

In this guide, we’ll dive deep into Froala’s robust toolbar customization options. You’ll learn how to override the default toolbar, create custom configurations based on device width, and even control the toolbar’s position, direction, and z-index. By the end, you’ll have the skills to craft a rich text editor that seamlessly integrates with your application’s design and workflow.

So if you’re ready to take your content creation tools to the next level, let’s get started unlocking the full potential of Froala’s customizable toolbar.

Custom toolbars for Froala

The Froala Default Toolbar

Let’s start with the following basic HTML template, including Froala’s core stylesheet and JavaScript files.

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0" />
        <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.min.css' rel='stylesheet' type='text/css' />


<style>

            .container{
                margin: 5% auto;
                width: 80%;
                display: block;
            }


        </style>
    </head>

    <body>
        <div class="container">
            <textarea id="editor">
                <h1>Let's build something beautiful</h1>
                <p>You can customize the Froala toolbar according to your use case. </p>
            </textarea>
        </div>

        <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.min.js'></script>

    </body>

</html>

Now, let’s initialize Froala using the default settings.

      <script> 

            var editor = new FroalaEditor('#editor');

        </script>

The Froala’s default toolbar has the following basic format options:

  • Formatting with Bold, Italic, Underline, Strikethrough, Subscript, and Superscript.
  • Clear formatting.
  • Increase and decrease indent.
  • Insert Horizontal Line.
  • History with Undo and Redo.
  • Select All.

Froala default toolbar

Froala’s modular architecture is based on plugins. If a plugin is not included or deactivated, its toolbar buttons will not be displayed.

By replacing the Froala stylesheet and JavaScript files in the above code with the packaged version, the toolbar will display all the default plugins’ toolbar buttons.

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0" />
        <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkg.min.css' rel='stylesheet' type='text/css' />


<style>

            .container{
                margin: 5% auto;
                width: 80%;
                display: block;
            }


        </style>
    </head>

    <body>
        <div class="container">
            <textarea id="editor">
                <h1>Let's build something beautiful</h1>
                <p>You can customize the Froala toolbar according to your use case. </p>
            </textarea>
        </div>

        <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>

    </body>

</html>
<script> 
    var editor = new FroalaEditor('#editor');
</script>

Froala Full Featured Toolbar

If you do not use all these features, you can include the stylesheets and JavaScript files of the plugins you want to use only. This way you can optimize your application performance. Here is a complete list of Froala’s plugins.

Customizing the Froala Toolbar

Overriding The Default Toolbar

There may be situations where you include a plugin file but don’t need to display its toolbar buttons, or you may want to display the buttons of a custom plugin. In either case, to override the default toolbar, you can use the toolbarButtons option. This option allows you to specify the buttons you want to display in the toolbar. By default, this option is set to

{

  'moreText': {

    'buttons': ['bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript', 'fontFamily', 'fontSize', 'textColor', 'backgroundColor', 'inlineClass', 'inlineStyle', 'clearFormatting']

  },

  'moreParagraph': {

    'buttons': ['alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', 'formatOL', 'formatUL', 'paragraphFormat', 'paragraphStyle', 'lineHeight', 'outdent', 'indent', 'quote']

  },

  'moreRich': {

    'buttons': ['insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome', 'specialCharacters', 'embedly', 'insertFile', 'insertHR']

  },

  'moreMisc': {

    'buttons': ['undo', 'redo', 'fullscreen', 'print', 'getPDF', 'spellChecker', 'selectAll', 'html', 'help'],

    'align': 'right',

    'buttonsVisible': 2

  }

}

As you can see, by default, it is an object that has four sub-objects, each representing a toolbar section.

  • moreText
  • moreParagraph
  • moreRich
  • moreMisc

Each of these four objects can have the following properties:

  • buttons: is an array that contains the buttons to be displayed in that section.
  • align: is a string that determines the position of a section on the toolbar. It can have a value of either “right” or “left”. If not specified, the default value is “left”.
  • buttonsVisible: is an integer that represents the number of buttons directly visible on the toolbar. Any additional buttons are hidden behind a “Display More” option.

If you prefer the classic toolbar where all buttons are visible, you can assign an array to the toolbarButtons option instead of an object. To separate buttons into groups, add each group in a separate array within the main array.

    var editor = new FroalaEditor('#editor',{
        toolbarButtons: [
            ['insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome', 'specialCharacters', 'embedly', 'insertFile', 'insertHR'],

            ['bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript', 'fontFamily', 'fontSize', 'textColor', 'backgroundColor', 'inlineClass', 'inlineStyle', 'clearFormatting'],

            ['alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', 'formatOL', 'formatUL', 'paragraphFormat', 'paragraphStyle', 'lineHeight', 'outdent', 'indent', 'quote'],

            ['undo', 'redo', 'fullscreen', 'print', 'getPDF', 'spellChecker', 'selectAll', 'html', 'help'],
        ]
    });

Full featured classic toolbar

In arrays, you can use the pipe character ‘|’ to add a vertical separator between options on the toolbar.

    var editor = new FroalaEditor('#editor',{
        toolbarButtons: [
            ['insertLink', 'insertImage', 'insertVideo', '|', 'insertTable', 'emoticons', 'fontAwesome'],

            ['bold', 'italic', 'underline', '|', 'strikeThrough', 'subscript', 'superscript',  'fontFamily', 'fontSize', 'textColor', 'backgroundColor', '|', 'inlineClass', 'inlineStyle', 'clearFormatting'],

        ]

    });

Froala toolbar with vertical separator

Use hyphens ‘-’ to add a horizontal separator between options on the toolbar.

   var editor = new FroalaEditor('#editor',{
        toolbarButtons: [
            ['insertLink', 'insertImage', 'insertVideo', '-', 'insertTable', 'emoticons', 'fontAwesome'],

            ['bold', 'italic', 'underline', '|', 'strikeThrough', 'subscript', 'superscript', '-', 'fontFamily', 'fontSize', 'textColor', 'backgroundColor', '|', 'inlineClass', 'inlineStyle', 'clearFormatting'],

        ]

    });

Froala custom toolbar with horizontal separator

If you have only one group of buttons, you can put them in a single array instead of the nested array.

    var editor = new FroalaEditor('#editor',{
        toolbarButtons: ['bold', 'italic', 'underline', 'alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', 'undo', 'redo', 'fullscreen', 'print', 'getPDF', 'insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome'],
        
    });

Froala custom toolbar

In this case, adding pipes ‘|’, will insert a white space between options.

   var editor = new FroalaEditor('#editor',{
        toolbarButtons: ['bold', 'italic', 'underline', '|', 'alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', '|', 'undo', 'redo', 'fullscreen', 'print', 'getPDF', '|', 'insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome'],
        
    });

Froala custom toolbar with white space

There are many ways to design your toolbar by just playing with the toolbarButtons option. This makes Froala Editor provide a highly customizable toolbar that allows you to tailor the available options to your specific needs. You can choose to display all buttons at once or group them into sections that can be expanded or collapsed. The toolbar can be aligned to the left or right, and you can control the number of directly visible buttons. This flexibility enables you to create a user interface that is both intuitive and efficient for your application.

Custom Froala Toolbar Based on The Screen or Editor Width

Froala provides several options to customize the toolbar buttons based on the screen or editor width. This allows you to optimize the user experience by showing the most relevant toolbar options for different device sizes.

The available options are:

  • toolbarButtonsMD: This option sets the list of buttons that appear in the rich text editor’s toolbar when the screen or editor width is larger than 992px and less than 1200px. If you don’t set this option, the toolbarButtons value will be used.
  • toolbarButtonsSM: This option sets the list of buttons that appear in the rich text editor’s toolbar when the screen or editor width is larger than 768px and less than 992px. If you don’t set this option, the toolbarButtonsMD value will be used.
  • toolbarButtonsXS: This option sets the list of buttons that appear in the rich text editor’s toolbar when the screen or editor width is less than 768px. If you don’t set this option, the toolbarButtonsSM value will be used.

By default, these options are responsive to the screen width. However, you can change this behavior to make the toolbar responsive to the editor width instead. To do this, set the toolbarResponsiveToEditor option to true. This can be useful if you want the toolbar to adapt to the size of the editor, rather than the overall browser window.

These options empower you with many benefits, such as:

  1. Optimized User Experience: By showing the most relevant toolbar options for different device sizes, you can provide a more intuitive and efficient editing experience for your users.
  2. Improved Performance: Reducing the number of toolbar buttons displayed on smaller screens can improve the overall performance and responsiveness of the Froala editor.
  3. Flexibility: The ability to customize the toolbar based on screen or editor width gives you greater control over the user interface, allowing you to tailor the editor to the specific needs of your application.

Here’s an example of how you can use these options to customize the toolbar:

var editor = new FroalaEditor('#editor', {
    toolbarResponsiveToEditor: true,
    toolbarButtonsMD: ['bold', 'italic', 'underline', 'align', 'formatOL', 'formatUL', 'insertLink', 'insertImage'],
    toolbarButtonsSM: ['bold', 'italic', 'underline', 'align'],
    toolbarButtonsXS: ['bold', 'italic', 'underline']
    });

In this example, the toolbar will display a larger set of buttons on medium and larger devices, a reduced set of buttons on small devices, and an even more minimal set of buttons on extra small devices. By making the toolbar responsive to the editor’s width, the layout and button visibility will adapt to the available space within the editor, providing an optimal user experience across different screen sizes.

Toolbar For RTL Language

When using Froala Editor with a right-to-left (RTL) language, you may want your editor toolbar buttons to start from the right. Froala provides the direction option to achieve this. By setting direction: 'rtl', the toolbar buttons will be displayed in the correct order and position for the RTL interface, providing a more natural and intuitive editing experience.

    var editor = new FroalaEditor('#editor', {
        toolbarButtons: ['bold', 'italic', 'underline', '|', 'alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', '|', 'undo', 'redo', 'fullscreen', 'print', 'getPDF', '|', 'insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome'],
        direction: 'rtl'    
    });

Froala RTL toolbar

Hide Toolbar Tooltips

You can also hide the tooltips that are shown when getting with the mouse over the buttons from the toolbar. To do this, set the tooltips option to false. However, we recommend keeping it enabled as tooltips can be helpful for users to understand the functionality of each toolbar button.

var editor = new FroalaEditor('#editor', {

 tooltips: false

});

Control Froala Toolbar Position

While you can configure the toolbar with more buttons or fewer buttons, another customization option is changing the toolbar position around the editor.

Bottom Toolbar

In some use cases, for example in chat applications or mobile-focused interfaces, it may be more desirable to position the toolbar at the bottom of the editor. This can be achieved by setting the toolbarBottom: true. This configuration will display the toolbar at the bottom of the editor, providing a more natural and intuitive layout for certain use cases.

Froala toolbar at bottom

Sticky toolbar

Another toolbar position option is the “sticky” toolbar, which keeps the toolbar visible at the top or bottom of the screen as the user scrolls through the content. This can be enabled by setting the toolbarSticky option to true. This ensures that the toolbar remains accessible and in view, even as the user scrolls, providing a more seamless editing experience. The sticky toolbar can be particularly useful when the editor is embedded within a larger page layout.

In this case, you can benefit from the toolbarStickyOffset option, which allows you to specify the vertical space in pixels from the top or bottom of the editor where the sticky toolbar should be fixed. This can be useful if you have other elements at the top of the page that you want the toolbar to remain below. By customizing the toolbar position, you can create a more intuitive and user-friendly interface that aligns with the specific needs of your application and its users.

var editor = new FroalaEditor('#editor', {

    toolbarButtons: ['bold', 'italic', 'underline', '|', 'alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', '|', 'undo', 'redo', 'fullscreen', 'print', 'getPDF', '|', 'insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome'],

    toolbarBottom: true,

    toolbarSticky: false,

    toolbarStickyOffset: 100,

    height: 1200

    });

Inline Toolbar

Alternatively, you can choose to display the toolbar in line with the editor content, rather than in a separate bar. This can be achieved by setting the toolbarInline option to true. You can learn more about how to use the inline mode in this guide.

Show information About Your Selection on The Toolbar

Another useful toolbar feature is the ability to display the font size, family, and paragraph format information of the user’s current selection on the toolbar. This can be enabled by setting the fontFamilySelection, fontSizeSelection, and paragraphFormatSelection options to true. This provides users with immediate feedback on the formatting of their selection, allowing them to quickly identify and adjust the font, size, or paragraph style as needed. By surfacing this information directly on the toolbar, the editing experience becomes more intuitive and efficient. These toolbar customization options give you the flexibility to tailor the Froala editor’s user interface to best suit the needs of your specific application and its users, enhancing the overall content creation and editing workflow.

var editor = new FroalaEditor('#editor', {

    toolbarButtons: ['bold', 'italic', 'underline', '|', 'alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', '|', 'undo', 'redo', 'fullscreen', 'print', 'getPDF', '|', 'insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome'],

    toolbarBottom: true,

    toolbarSticky: false,

    toolbarStickyOffset: 100,

    height: 1200,

    fontFamilySelection: true,

    fontSizeSelection: true,

    paragraphFormatSelection: true

});

See an example of show selection details in the Froala toolbar.

Control Multiple Editors From a Shared Toolbar

Froala Editor allows you to control multiple editors on the same page using a shared toolbar. This can be useful when you have multiple rich text editors on a single page and want to provide a consistent user experience.

To achieve this, you can use the toolbarContainer option. This option allows you to specify a CSS selector for an external container where the toolbar will be placed. All the editors on the page will then share this common toolbar.

Here’s an example:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0" />
        <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />


<style>

            .container{
                margin: 5% auto;
                width: 80%;
                display: block;
            }


        </style>
    </head>

    <body>
        <div class="container">
            <div id="toolbarContainer"></div>
            <p>Some dummy content.</p>
            <p>Some dummy content.</p>

            <h2>Editor 1</h2>

            <textarea id="editor1">
                <h1>Let's build something beautiful</h1>
                <p>You can customize the Froala toolbar according to your use case. </p>
            </textarea>
            <p>Some dummy content.</p>

            <h2>Editor 2</h2>
            <textarea id="editor2">
                <p>This editor toolbar is in another Div.</p>
            </textarea>
        </div>

        <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>


        <script> 
            var editor1 = new FroalaEditor('#editor1', {
                toolbarButtons: ['bold', 'italic', 'underline', '|', 'alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', '|', 'undo', 'redo', 'fullscreen', 'print', 'getPDF', '|', 'insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome'],
                toolbarContainer: '#toolbarContainer'
            });
        
            var editor2 = new FroalaEditor('#editor2', {
                toolbarButtons: ['bold', 'italic', 'underline', '|', 'alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', '|', 'undo', 'redo', 'fullscreen', 'print', 'getPDF', '|', 'insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome'],
        
                toolbarContainer: '#toolbarContainer'
            });
        </script>
    </body>

</html>

Shared toolbar

In the above code, we have a shared toolbar container with the ID `#toolbarContainer`. Both editors, `editor1` and `editor2`, are configured to use this shared toolbar container by setting the toolbarContainer option and configuring the toolbarButtons to have the same buttons in both editors. This allows the toolbar to be displayed in a single location, providing a consistent user interface across multiple editors on the same page.

If the toolbarButtons option has different settings for each editor, it will result in two separate toolbars – one for each editor.

By sharing the toolbar, any insertion made in the editor (e.g., inserting an image) will be reflected in the active editor.

The Froala Toolbar Is Not Showing

If the toolbar is not appearing, the problem is most likely in the configuration of the toolbar option. However, sometimes the problem is the toolbar is hidden under other page elements. In this case, you can use the Froala zIndex option to fix this. This option sets the zIndex on the editor toolbars and popups.

For example, if the toolbar is hidden behind a fixed header, you can set the z-index option to a higher value to ensure the toolbar is displayed on top. This can be done by setting the zIndex option when initializing the Froala Editor:

var editor = new FroalaEditor('#editor', {

  zIndex: 2000 // Set a higher z-index value

});

Adjusting the z-index can help resolve issues where the toolbar is obscured by other page elements, ensuring the editor’s functionality remains accessible and intuitive for users.

Unleash the Power of Froala’s Customizable Toolbar

Froala’s flexible and customizable toolbar provides a powerful way to tailor the rich text editor to your specific needs. You can optimize the toolbar layout for different screen sizes and editor widths. You also have the ability to control the toolbar position. This ensures an intuitive and efficient editing experience across devices.

Additional customization options, such as setting the toolbar direction and displaying selection details, give you even greater flexibility to create a polished, user-friendly interface.

By taking advantage of Froala’s robust toolbar customization capabilities, you can craft a rich text editing experience that seamlessly integrates with your application’s design and functionality. Unlock the full potential of Froala and create content management solutions that delight your users.

Ready to build your custom Froala toolbar? Get started today and elevate your content creation workflows!

Rich Text to HTML Editors: Making Web Development Easier with Code View

Have you ever wondered how websites let you write fancy text without knowing HTML? That’s where rich text to HTML editors come in handy. These tools are super useful for web developers. Today, we’re going to explore how these editors work, especially the cool “code view” feature.

 

Key Takeaways

  • Rich text editors let anyone create nice-looking content without writing HTML
  • Code view lets developers see and edit the actual HTML
  • Switching between normal view and code view gives more control over content
  • You can make things happen automatically when someone changes the code view
  • Adding code view makes content editing more powerful and flexible

What Are Rich Text to HTML Editors?

First of all, let’s talk about rich text editors. These are tools that make it easy for people to write fancy text on websites. You can make words bold, add pictures, and organize your writing without knowing any complicated code. Behind the scenes, these editors turn your writing into neat HTML code.

Why Code View is Awesome

Now, while most people are happy just writing their content, sometimes developers need to see what’s happening under the hood. That’s where code view comes in. It’s like peeking behind the curtain to see how the magic happens.

Here’s why code view is so cool:

  1. You can fix tricky problems that you can’t see in the normal view
  2. You can add special code to make your content look exactly how you want
  3. It helps make websites easier to use for people with disabilities
  4. You can clean up messy code to make your website faster

How to Use Code View

Let’s look at how you might set up code view in a rich text editor. Don’t worry if this looks complicated – it’s just an example!

var editor = new FroalaEditor('#froala', {
  pluginsEnabled: ['codeView'],
  codeViewKeepActiveButtons: ['selectAll'],
  events: {
    'codeView.update': function () {
      document.getElementById("eg-previewer").textContent = this.codeView.get();
    }
  }
});

This code does a few things:

  • Enable code view: This allows users to directly interact with the code.

  • Maintain “select all” functionality: Ensure users can still easily select all code within code view.

  • Dynamic response to code changes: Trigger an action or update based on modifications made in the code view.

Making Things Happen Automatically

One of the coolest things about code view is that you can make stuff happen automatically when someone changes the code. For example, you could update a preview of your website in real-time as you type.

A Real-Life Example

Let’s put it all together with a real example. Imagine you’re building a website where people can write blog posts. You want to give them a normal editor, but also let them see the HTML if they want to. Here’s how that might look:

<h1>Code View Plugin</h1>
<div id='froala'>
 Open the code viewer, edit the code and close the code view mode, this will trigger the codeView.update event and in this example, the HTML code inside the code view mode will appear under the editor.
</div>
<br/>
<pre id="eg-previewer">
</pre>

And here’s the code that makes it work:

 

var editor = new FroalaEditor('#froala', {
  pluginsEnabled: ['codeView'],
  codeViewKeepActiveButtons: ['selectAll'],
  events: {
    'codeView.update': function () {
      document.getElementById("eg-previewer").textContent = this.codeView.get();
    }
  }
});

 

This code sets up an editor where people can write normally. But if they want to, they can also see and edit the HTML code. Whenever they make a change in code view, it automatically updates a preview of the HTML below the editor.

Wrapping Up

In conclusion, rich text to HTML editors with code view are super helpful tools for web developers. They make it easy for anyone to create nice-looking content, while still giving developers the power to tweak things behind the scenes.

By adding code view to your projects, you’re giving yourself and your users more control and flexibility. Whether you’re building a blog, a website builder, or any other kind of web app, consider using a rich text editor with code view. It’s like having the best of both worlds – easy for beginners, but powerful for experts!

 

Enhance Your Content with beautiful Photos Using the Image Tui Plugin

TUI plugin - edit images and add filters

WYSIWYG editors simplify web content creation by allowing users to format their content without having coding skills. For instance, you can insert images by uploading them through a simple user interface and see how they will look on the web page. The editor is responsible for writing the HTML code to display the image.

In this article, we aim to enhance the user experience by enabling image manipulation before insertion in the editor. Users can crop, flip, rotate, draw, and add shapes, icons, text, mask filters, and image filters using the Toast UI Image editor. This editor is integrated flawlessly with the Froala editor using its Image Tui Plugin.

With the Image Tui Plugin, users can effortlessly enhance their content with visually striking images that perfectly match their desired aesthetic. This empowers content creators to produce more engaging and visually appealing web pages without the need for specialized image editing software. Let’s learn how it works.

What is The Toast UI Image Editor?

The Toast UI Image Editor is a free, open-source JavaScript tool for editing images using HTML5 Canvas. It offers a user-friendly interface and powerful image filters, making it a convenient tool for image editing. The editor is widely supported across major web browsers, including Chrome, Internet Explorer 10+, Edge, Safari, and Firefox. Its responsive design ensures a good user experience on screens with a minimum size of 550 x 450 pixels. The editor theme can be easily customized using the editor API.

The Toast UI Image Editor Features

The editor comes with a wide range of great photo manipulation features, suitable for most use cases:

  • Load image to canvas
  • Undo/Redo (With shortcut)
  • Download
  • Reset
  • Delete Object(Shape, Line, Mask Image…)
  • Crop
  • Flip
  • Rotation
  • Resize
  • Free drawing
  • Line drawing
  • Shape
  • Icon
  • Text
  • Mask Filter
  • Image Filter
    • Grayscale
    • Invert
    • Sepia
    • Blur Sharpen
    • Emboss
    • Remove-white
    • Brightness
    • Noise
    • Pixelate
    • Color filter
    • Tint
    • Multiply
    • Blend

Integrating The Toast UI Image Editor With The Froala WYSIWYG Editor

The integration between the Toast UI Image Editor and Froala WYSIWYG editor is very simple, thanks to the Image Tui plugin.

Include Froala Editor Files

Let’s begin with a basic setup of Froala editor in a simple HTML web page:

  1. Include Froala Stylesheet and JavaScript files.
  2. Add HTML element to load editor at.
  3. Add a script with the Froala initialization code.
<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0" />
        <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.min.css' rel='stylesheet' type='text/css' />
        <style>
            body{
                background-color: black;

            }
            .container{
                margin: 5% auto;
                width: 80%;
                display: block;
            }

            .container h1{
                color: #fff;
                text-align: center;
            }

        </style>
    </head>

    <body>
        <div class="container">
            <h1 class="header">Let's build something beautiful</h1>
            <div id="example"></div>
        </div>

        <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.min.js'></script>  
        <script> 
            var editor = new FroalaEditor('#example');
        </script>
    </body>

</html>

This will load the basic Froala editor features.

Froala core editor

Include The Toast UI Image Editor Files

To use the Toast UI Image Editor, include its stylesheet and JavaScript files.

        <link rel="stylesheet" href="https://uicdn.toast.com/tui-color-picker/latest/tui-color-picker.css">
        
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.7/fabric.min.js"></script>
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/tui-code-snippet.min.js"></script>
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/tui-image-editor.min.js"></script>

Include The Froala TUI Image Plugin Files

The Froala TUI Image plugin requires Froala’s Image plugin to be active. Let’s include the stylesheet and JavaScript files for the image and TUI plugins.

        <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/plugins/image.min.css' rel='stylesheet' type='text/css' />
        <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/third_party/image_tui.min.css' rel='stylesheet' type='text/css' />
    
        <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/plugins/image.min.js'></script> 
        <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/third_party/image_tui.min.js'></script>

How It Works

When you run the editor with the above setup, you can edit images using the Toast UI Image Editor by following these steps:

  1. Insert an image into the editor.
  2. Click on the image to edit it.
  3. Click on the “Advanced Edit“ button from the displayed popup.
  4. Start editing the image using the Toast UI Image Editor.
  5. Save changes to use the edited image instead of the original one.

Froala TUI plugin

Customizing The Froala Editor

While customizing the editor, keep your eye on the following options to avoid accidentally deactivating the Toast UI Image Editor.

pluginsEnabled

This option tells the editor which plugins are enabled and can be used by users. If you are customizing this option, make sure you have added the image and the imageTUI plugins.

var editor = new FroalaEditor('#example',{

    pluginsEnabled: ['image', 'imageTUI'],

});

toolbarButtons

This option controls the buttons displayed on the Froala toolbar. If you are customizing this setting, ensure that you have included the InsertImage button.

var editor = new FroalaEditor('#example',{

    pluginsEnabled: ['image', 'imageTUI'],

    toolbarButtons: ['insertImage'],

});

imageEditButtons

This option determines the buttons shown on the Edit Image popup. Make sure the imageTUI button is included. This will allow users to open the TUI image editor.

var editor = new FroalaEditor('#example',{

    pluginsEnabled: ['image', 'imageTUI'],

    toolbarButtons: ['insertImage'],

    imageEditButtons: ['imageReplace', 'imageAlign', 'imageCaption', 'imageRemove', 'imageTUI']

});

Customizing The TUI Plugin

The Toast UI Image Editor has a powerful API that helps customize the features displayed to the user and the editor UI. When the Toast UI Image Editor is integrated into the Froala editor through the TUI plugin, you can customize the TUI editor by utilizing the imageTUIOptions option.

            var editor = new FroalaEditor('#example',{
                pluginsEnabled: ['image', 'imageTUI'],
                toolbarButtons: ['insertImage'],
                imageEditButtons: ['imageReplace', 'imageAlign', 'imageCaption', 'imageRemove', 'imageTUI'],
                imageTUIOptions: {
                    includeUI: {
                        initMenu: "filter",
                        menuBarPosition: "right",
                        theme: {
                            "menu.activeIcon.path": "https://cdn.jsdelivr.net/npm/[email protected]/dist/svg/icon-b.svg",
                            "menu.disabledIcon.path": "https://cdn.jsdelivr.net/npm/[email protected]/dist/svg/icon-a.svg",
                            "menu.hoverIcon.path": "https://cdn.jsdelivr.net/npm/[email protected]/dist/svg/icon-c.svg",
                            "menu.normalIcon.path": "https://cdn.jsdelivr.net/npm/[email protected]/dist/svg/icon-d.svg",
                            "submenu.activeIcon.name": "icon-c",
                            "submenu.activeIcon.path": "https://cdn.jsdelivr.net/npm/[email protected]/dist/svg/icon-c.svg",
                            "submenu.normalIcon.name": "icon-d",
                            "submenu.normalIcon.path": "https://cdn.jsdelivr.net/npm/[email protected]/dist/svg/icon-d.svg"
                        }
                    }
                }

            });

Do I need to subscribe to a specific plan for using the Froala TUI plugin?

The Froala TUI plugin, as well as other Froala plugins, are available in any of the Froala’s plans. Check our pricing page and select the plan that best fits your needs. Froala’s flexible licensing options ensure you can utilize the full capabilities of the TUI plugin, tailored to your specific requirements, with no additional costs or restrictions.

Does Froala Offer a Free Trial?

You can try Froala for free by downloading the editor and using it on your localhost or staging site. The unlicensed editor displays an alert message under the toolbar; however, it doesn’t restrict any features of the editor. Once you are ready to use the editor in production, purchase a license to get the API key and remove the unlicensed message.

Elevate Your Content with Visually Stunning Images

The integration of the Toast UI Image Editor with the Froala WYSIWYG editor through the Image TUI plugin is a game-changer for content creators. This powerful combination empowers you to effortlessly enhance your web content with visually striking, professionally edited images.

No longer are you limited to basic image insertion. With the Toast UI Image Editor, you can unleash your creativity, cropping, flipping, rotating, drawing, and applying a wide range of filters to your images – all within the familiar Froala editor interface. This allows you to produce more engaging, visually appealing content without the need for specialized image editing software.

So what are you waiting for? Start your Froala WYSIWYG editor free trial today. Captivate your audience, boost your brand, and take your online presence to new heights. The tools are at your fingertips – all you need to do is unlock their potential.

The Art of Fluid Editing: Froala’s Draggable Plugin

Drag and drop with Froala

Nowadays, users are looking for convenient ways to edit their content. In response to this need, professional WYSIWYG editors with advanced capabilities, such as Froala, have become increasingly popular. For example, the Froala draggable plugin allows moving images and videos within the editor by dragging them, resulting in easily reordering the content and improving the overall content editing experience.

In this article, we will explore the Froala draggable plugin in depth. We will look at setting up the plugin, its options, and different usage examples.

Drag and drop with Froala

What is the Froala Draggable Plugin?

The Froala draggable plugin adds the capability to drag content such as images and videos inside the Froala editor. This allows users to move and rearrange the content using their mouse or touch screen. Using the Froala draggable plugin has several advantages such as

  • Improved user experience:
    Adding a drag-and-drop feature makes your application more user-friendly and improves the overall user experience.
  • Increased productivity
    Dragging content using a mouse or touch screen is much faster than cutting content and re-pasting it. As a result, users will be able to complete more tasks in the same time frame.

Installation and Setup of Froala Draggable Plugin

To set up the Froala Draggable plugin, you have to include its script and stylesheet files alongside the core Froala editor scripts and stylesheet files

<!-- Froala core editor Files -->
<link href='{url_based_on_your_download_option}/css/froala_editor.min.css' rel='stylesheet' type='text/css' />

<script type='text/javascript' src='{url_based_on_your_download_option}/js/froala_editor.min.js'></script>


<!-- Froala Draggable plugin files -->
<link href='{url_based_on_your_download_option}/css/plugins/draggable.min.css' rel='stylesheet' type='text/css' />

<script type='text/javascript' src='{url_based_on_your_download_option}/js/plugins/draggable.min.js'></script>

Note that if we use the .pkgd version of the Froala editor, you do not have to include Draggable plugin scripts and stylesheet files separately. The .pkgd version already includes all Froala’s default plugin files.

Once the plugin files are included, it will be active by default when initializing the editor

new FroalaEditor('#HTMLElement');

However, if you’re customizing the pluginsEnabled option, you must include the Draggable plugin:

new FroalaEditor('#HTMLElement',{

     pluginsEnabled: ['image', 'link', 'video', 'draggable', 'print']

});

Using the Draggable Plugin

If the Draggable plugin is enabled and there are images or videos inside the editor, users can drag these elements as follows:

  • Click on the element.
  • Drag the element into a new position within the editor.
  • Release the element.

Dragging elements as described above is impossible if the Draggable plugin is disabled.

Customizing the Draggable Plugin

Options

The Draggable plugin provides developers with a dragInline API option. This option allows developers to control how the dragged elements are positioned within the editor. When set to true, the dragged items can be placed inside inline elements, such as text. Disabling this option ensures that the dragged elements are positioned between block-level tags. This provides more control over the layout and structure of your content.

new FroalaEditor('#HTMLElement',{
     dragInline: false,
     pluginsEnabled: ['image', 'link', 'video', 'draggable', 'print']

});

draginline
draginline: true

 

draginline-false
draginline: false

 

Events

The plugins register two events:

  • The element.beforeDrop event is fired when the user starts dropping the dragged element into a new or the same position (by releasing a mouse button or hitting the escape key).
  • The element.dropped event is fired when the element is dropped either in a new or the same position.
new FroalaEditor('div#froala-editor', {
  dragInline: false,
  pluginsEnabled: ['image', 'link', 'draggable', 'print'],
  events: {
    "element.beforeDrop": function(element) {
      console.log("beforeDrop");
    },
    "element.dropped": function(element, t) {
      console.log("droppped");
    },

  }
})

Both events pass the dragged element as the first argument of the callback function.

If more control is required over the dragging and dropping process, JavaScript events can be utilized, such as:

  • drag
  • dragend
  • dragenter
  • dragleave
  • dragover
  • dragstart
  • drop

To utilize these events, register an event handler for these events inside the editor’s initialized event using the on method.

new FroalaEditor('div#froala-editor', {
  dragInline: false,
  pluginsEnabled: ['image', 'link', 'draggable', 'print'],
  events: {
    "element.beforeDrop": function(element) {
      console.log("beforeDrop");
    },
    "element.dropped": function(element, t) {
      console.log("droppped");
    },
    'initialized': function() {
      // Do something here.
      var editor = this;

      editor.events.on('drop', function(dropEvent) {
        console.log("drop");
        console.log(dropEvent);

      });
    }
  }
})

Comparison of dragging feature between TinyMCE and Froala

At the time of writing this article, I went to the official TinyMCE full feature example page, I tried to drag the TinyMCE logo image but it didn’t move. Clicking on the image to drag it makes the image selected, but once I try to move it down, it selects the text below instead of dragging the image.

drag-and-drop inTinyMCE

I copied the TinyMCE editor content and pasted it into the Froala editor full-featured example, moving the TinyMCE logo by drag and drop was a piece of cake.

Drag-and-drop in Froala

Moreover, unlike Froala:

  • TinyMCE doesn’t provide options to customize drag-and-drop behavior.
  • TinyMCE only supports browser-native dragging events.

Overall, Froala provides a better user drag-and-drop experience.

Do I need to subscribe to a specific plan for using the Froala Draggable plugin?

The Froala draggable plugin, as well as other Froala plugins, are available in any of the Froala’s plans. Check our pricing page and select the plan that best fits your needs. Froala’s flexible licensing options ensure you can utilize the full capabilities of the draggable plugin, tailored to your specific requirements, without any additional costs or restrictions.

What is the difference between Froala’s annual and perpetual licenses?

Froala’s annual license lets you use the Froala editor for a full calendar year. Within this year, you can update your editor to the new releases. After that, you need to renew your license to continue using the editor in your product.

Froala’s perpetual license lets you use any version of the Froala editor that was released within one year of your license purchase, forever. To use versions that were released after that, you can renew your license at a discounted cost.

Can I test the editor before purchasing a license?

You may download the editor from our download page and test it at any time, without spending money. While testing, an unlicensed message will be displayed, however, it doesn’t limit any of the editor’s features. Once you are ready to use the editor in production, purchase a license to get the API key and remove the unlicensed message.

Conclusion

The Froala draggable plugin offers a seamless and customizable drag-and-drop experience, surpassing the capabilities of TinyMCE’s dragging functionality. With options to control the positioning of dragged elements and events to monitor the dragging process, Froala provides developers with greater control over the content structure. Froala’s flexible licensing, including annual and perpetual options, ensures the draggable plugin can be utilized effectively without additional costs or restrictions, making it a compelling choice for content-rich web.

 

Froala Word Count Plugin: A Comprehensive Guide

word counter thumbnail

Content duration regulation is an absolute necessity in digital content development. The precise word count is essential for adhering to specifications, optimizing search engines, and enhancing readability, regardless of whether you are a writer, editor, or marketer.

With the addition of the remarkable Word Count module in version 4.2, the well-known WYSIWYG (What You See Is What You Get) HTML editor Froala Editor makes it simpler to monitor your real-time word consumption. Using the Froala Word Count feature to its fullest capacity is the subject of this article.

Understanding the Froala Word Count Plugin

The Froala Word Count plugin is an extension for the Froala editor that functions flawlessly. Upon activation, the plugin provides real-time visibility into the word count of your content.

Here’s a breakdown of the primary features supplied by the Froala word count plugin:

  • Real-time Word Count: The plugin continuously monitors your content and displays the precise word count. This eliminates the need to manually count words or rely on external tools, resulting in greater accuracy and efficiency.
  • Clear Visibility: The word count is usually displayed in a specific section of the editor’s interface, making it easily available for quick reference. You can concentrate on your writing without switching between windows or applications.
  • Configurable Limits: Set maximum word to ensure your content stays within desired bounds. However, character limits can be modified via a character plugin.
  • Seamless Integration: Easily integrates with other Froala plugins and tools.

Advantages of Employing the Froala Word Count Plugin

There are numerous benefits to incorporating the Froala word count feature into your writing workflow:

  1. Keep Up with Word Limit: By religiously following up on the number of your written words, you are in a position to ensure that your published document will meet this limit. This advantage is highly appreciated by those who do freelance writing, develop content and engage in academic writing because they have to follow the exact word count boundary.
  2. Enhanced Efficiency in Writing: The writing process is streamlined by providing a real-time word count and no longer requires external tools or manual word counting. This enables you to focus uninterrupted on the composition of your content.
  3. Enhanced Content Planning and Structure: The ability to ascertain the current word count provides the means to strategize and organize content efficiently. You can guarantee a proportionate and balanced structure by assigning word counts to distinct sections of your writing.
  4. Fosters’ Brevity and Clarity: Good writers are conscious of their word counts, which helps them create brief texts that serve the purpose they want to communicate. The number of words can serve as a tacit reminder to avoid repetition or superfluous information in an essay.

Configuring Froala Editor with the Word Count Plugin

Before utilizing the Froala Word Count function, you must incorporate the Froala Editor into your project. Proceed by following these steps:

Step 1: Include Froala Editor Files

Froala Editor files can be incorporated into a project via a CDN or downloaded from the Froala website. How to accomplish this with a CDN:

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Froala Editor with Word Count Plugin</title>
    <!-- Include Froala Editor style files -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
</head>
<body>

<div id="editor"></div>

<!-- Include Froala Editor JS files -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/js/froala_editor.pkgd.min.js"></script>

<!-- Initialize the Froala Editor -->
<script>
    new FroalaEditor('#editor', {
      // Insert the Word Counter Plugin here
    });
</script>

</body>
</html>

 

Step 2: Enable the Word Count Plugin

In the initialization script, enable the wordCounter plugin by including it in the pluginsEnabled array:

 

<script>
    new FroalaEditor('#editor', {
        pluginsEnabled: ['wordCounter']
    });
</script>

 

You have effectively integrated the Word Count feature of the Froala Editor into your project by following these steps.

Customizing the Word Count Display

Froala Editor provides the capability to modify the appearance of the word count. You can display the word count and maximum count limit or both. Here’s how to accomplish it:

Displaying Word Count

To show the word count, the initialization script can be modified as follows:

 

$(function() {
  $('#editor').froalaEditor({
    pluginsEnabled: ['wordCounter'],
    wordCounterCount: true
  });
});

 

Hide Word Count

To hide the word count, the initialization script can be modified as follows:

 

 

$(function() {
  $('#editor').froalaEditor({
    pluginsEnabled: ['wordCounter'],
    wordCounterCount: false
  });
});

 

 

In addition, the Word Count function permits the configuration of maximum limits for words. This feature is especially beneficial in guaranteeing that the duration of your content adheres to designated criteria.

Setting a Maximum Word Limit

In the initialization script, include the ‘wordCounterMax’ parameter to establish a maximum word limit, in our case we have set the limit to 200:

 

$(function() {
  $('#editor').froalaEditor({
    pluginsEnabled: ['wordCounter'],
        wordCounterCount: true,
        wordCounterMax: 200,
  });
});

 

 

Track Your Word Count with Froala’s Word Count Plugin

Froala’s Word Count plugin is invaluable for those who must monitor every word of their content. It features configurable limits, real-time updates, and customizable displays to facilitate the efficient and streamlined management of your writing metrics.

By adhering to the instructions in this tutorial, one can effortlessly incorporate and personalize the Word Count plugin in Froala Editor, guaranteeing that the content consistently satisfies the intended criteria. Regardless of your professional background as a developer, writer, or marketer, attaining proficiency in this feature will undeniably improve your content creation workflow.

Optimizing React CMS Applications With Lazy Loading of The React WYSIWYG Editor

lazy-loading Froala in React CMS

React CMS applications are popular, especially in modern web development. One of their main components is the React WYSIWYG editor, which helps content creators generate and organize content within the CMS.

In a React CMS application, initializing the React WYSIWYG editor after clicking an external button can improve the user experience in case the editor is not needed immediately when the page loads. This approach, known as lazy loading, helps to speed up the initial page load time, which is a critical factor in user experience.

Why are React CMS Applications popular?

React CMS Applications are popular because they offer a powerful combination of React’s component-based architecture and the flexibility of a Content Management System (CMS), making them a go-to choice for developers looking to build dynamic, scalable, and efficient web applications.

React CMS applications are popular for several reasons:

  1. Scalability: React CMS applications can handle large amounts of traffic and data without breaking down, making them perfect for businesses that experience sudden spikes in traffic or have many users.
  2. Flexibility: Whether it’s a change in design or functionality, React CMS applications can be easily customized and adapted to meet the specific needs of a business.
  3. Fast development cycles: developers can quickly create and deploy new features and updates in React CMSs, allowing businesses to respond fast to changing market demand and customer needs.
  4. Seamless user experience: React CMS applications provide a seamless user experience, with fast loading times and intuitive navigation, increasing customer satisfaction and loyalty.
  5. Community support: React CMS has a large and active community of developers, which means plenty of resources are available for troubleshooting and solving problems.
  6. Integration with other technologies: React CMS can be easily integrated with other technologies, such as server-side rendering, GraphQL, and state management libraries, allowing developers to create complex and sophisticated applications.
  7. Performance: React CMS applications are optimized for performance, using techniques such as lazy loading and code splitting, to ensure that the application loads quickly and runs smoothly.

Why Does React CMS Use WYSIWYG Editors?

WYSIWYG (What You See Is What You Get) editors enable users to create and edit content while applying the inserted format in real time. Moreover, it doesn’t require users to be familiar with coding. This streamlines the content creation and management process, making it more accessible for non-technical users. Professional WYSIWYG editors can provide your team with many editing features, helping them create professional-looking content easily. The powerful React WYSIWYG editor, Froala, has over 100 features.

How to Lazy Load Froala WYSIWYG Editor in React application

Let’s look at how to use lazy loading to keep the Froala React WYSIWYG Editor from loading until needed.

Prerequisites

  • JavaScript (including some of the newer, ES2015 features)
  • Basic understanding of React
  • Node.js and npm installed

Setting Up The React Project

If you don’t already have a React project set up, the create-react-app makes it easy to create one:

npm uninstall -g create-react-app

npm install -g create-react-app

npx create-react-app lazy-load-froala-app

Cd lazy-load-froala-app

Next, install the react-froala-wysiwyg package, which provides the Froala Editor component for React:

npm install react-froala-wysiwyg --save

The --save flag is important to add the React Froala WYSIWYG editor package to the dependencies in your package.json file. This ensures that the Froala editor is included in your deployed application.

Integrating The Editor

You should integrate the editor into where you want to display the editor. For simplicity, we will suppose we want to display on the homepage. Edit the app.js file.

  • Import the editor CSS stylesheet so the editor UI appears correctly.
  • Import the FroalaEditorComponent so you can use the component inside the app function.
  • Import the required plugins.
  • Add the customization options
  • Add initialization text
import React, { useState  } from 'react';
import './App.css';

//froala_style.min.css: Only needed if you display the editor content outside the rich text editor to preserve the look of the edited HTML.
import 'froala-editor/css/froala_style.min.css';

//froala_editor.pkgd.min.css: Contains the editor UI styles, such as the toolbar, buttons, popups, etc.
import 'froala-editor/css/froala_editor.pkgd.min.css';

// Import all Froala Editor component;
import FroalaEditorComponent from 'react-froala-wysiwyg';

// Import all Froala Editor plugins;
import 'froala-editor/js/plugins.pkgd.min.js';

// Render Froala Editor component.
function App() {
  const [model, setModel] = useState("the integration of CMS with React has become a significant trend in web development, offering developers the best of both worlds: the robustness of a CMS and the agility of React.");

  const handleModelChange= (event) =>{

    setModel(event)
  
  }  


  //Froala custom options
    let config = {
      heightMin: 300,
      events : {
        'contentChanged' : function(e, editor) {
          console.log('test');
        }
      }
    };

    return (
    <div className="App">
      <header className="App-header">
      <h1>Lazy load Froala app</h1>
        <FroalaEditorComponent
            model={model}
            onModelChange={handleModelChange}
            config={config}
          />

      </header>
    </div>
  );
}

export default App;

Running the app will display the Froala editor.

React WYSIWYG editor

For more explanation about the above code, refer to the “Integrate Froala with React“ guide.

Displaying the Editor on the Button Click

To display the editor on click, we need to implement the following:

  • Set up a state to track whether Froala should be displayed or removed.
  • Create a button that, when clicked, updates the state to initialize Froala.
    • A button to display the editor.
    • A button to hide the editor and display its content only.
  • Conditionally render the Froala Editor based on the state.
  • Import the FroalaEditorView component to display the editor content outside the editor correctly.
import React, { useState  } from 'react';
import './App.css';

//froala_style.min.css: Only needed if you display the editor content outside the rich text editor to preserve the look of the edited HTML.
import 'froala-editor/css/froala_style.min.css';

//froala_editor.pkgd.min.css: Contains the editor UI styles, such as the toolbar, buttons, popups, etc.
import 'froala-editor/css/froala_editor.pkgd.min.css';

// Import core Froala Editor component;
import FroalaEditorComponent from 'react-froala-wysiwyg';

// Import the component to display the editor content outside the editor;
import FroalaEditorView from 'react-froala-wysiwyg/FroalaEditorView';

// Import all Froala Editor plugins;
import 'froala-editor/js/plugins.pkgd.min.js';

// Render Froala Editor component.
function App() {
  const [model, setModel] = useState("the integration of CMS with React has become a significant trend in web development, offering developers the best of both worlds: the robustness of a CMS and the agility of React.");

  const handleModelChange= (event) =>{

    setModel(event)
  
  }  

  //Set up a state to track whether Froala should be displayed or removed.
  const [initializeEditor, setInitializeEditor] = useState(false);

  const handleButtonClick = (flag) => {
  setInitializeEditor(flag);
  };

  //Froala custom options
    let config = {
      heightMin: 300,
      events : {
        'contentChanged' : function(e, editor) {
          console.log('test');
        }
      }
    };

    return (
    <div className="App">
      <header className="App-header">
      <h1>Lazy load Froala app</h1>
      {
        //Conditionally render the Froala Editor based on the state.
      }
        { initializeEditor && <FroalaEditorComponent
            model={model}
            onModelChange={handleModelChange}
            config={config}
          />
        }
        
        { !initializeEditor && <FroalaEditorView
          model={model}
        />
        }

      { 
      // Add button
       }
      <button onClick={() => handleButtonClick(true)}>Edit Content</button>
      <button onClick={() => handleButtonClick(false)}>View Content</button>


      </header>
    </div>
  );
}

export default App;

React CMS

Conclusion

Enabling the Lazy loading technique in React CMS improves the overall user experience of your application. Ask yourself if you need the Froala React WYSIWYG Editor component to be initialized immediately after the page loads. If not, implement the lazy load technique as described above.

Try it yourself and once you are ready to use Froala in production, subscribe to the plan that suits you.
Download Froala Editor

 

Gemini AI Integration in Froala Editor: AI-powered Chat and Generate Feedback Features

Gemini AI Integration in Froala WYSIWYG Editor

Would you like to give your users the power of using AI inside their WYSIWYG editor to help them compose content, rewrite some blocks, or get feedback on their writing? That would be easy if you have a powerful WYSIWYG editor that makes it easy to extend its functionality such as Froala. Since it was made by developers for developers, Froala has been built with a modular architecture based on plugins making it easy to add new functions to the editor. Choosing Froala helps you to provide your users with new features developed for your specific use case. Moreover, you will not miss new technologies waiting for the editor team to build it for you, you can easily build it for yourself.

Generative AI tools, such as Gemini, are becoming an essential part of any product, used to create content, looking for success. “Powered by AI” is a successful marketing statement that helps in promoting your product to many categories.

Integrating Froala with ChatGPT or Gemini is a magic recipe for incorporating success for your product and it’s a piece of cake. In this article, you will learn how to build a custom Froala plugin for integrating Gemini into your Froala editor. We will add a popup to chat with Gemini and a button to allow users to receive SEO feedback on various aspects of their writing.

Froala meets AI

What is Gemini?

Gemini is an AI-powered chat service developed by Google to enhance creativity and productivity. It’s designed to assist with writing, planning, learning, and more, leveraging Google’s AI technology. Initially introduced as Bard, it functions similarly to a conversational chatbot and uses information from the web to provide fresh, high-quality responses.

How to integrate Gemini With Froala?

To integrate Gemini into 3rd party tools, you need first to get a Gemini API key. This API key should be kept secret for security purposes. That’s why we strongly recommend that you call the Google AI Gemini API only server-side. If you embed your API key directly in your web app or fetch it remotely at runtime, you risk potentially exposing your API key to malicious actors. That’s why we will perform this tutorial in the Node.js environment using Express Framework.

Integrate Froala with Express Framework

We already created a tutorial about using the Froala editor in the Node.JS server using Express Framework. We will make a quick recap here but for more details, you can go back to that tutorial.

Create a new Node.js app

npm init

Set the entry point to “app.js”

Install Dependencies

Install the Express framework, Embedded JavaScript templates (EJS), and Froala WYSIWYG editor

npm install froala-editor ejs express

Set up the Express Framework

Create a new file named “app.js” in the root directory of our project. Open “app.js” and add the following code:

var express = require('express');

var app = express();

// Set EJS as the view engine
app.set('view engine','ejs');

//Froala editor CSS & JS files
app.use('/froalacss',express.static(__dirname+'/node_modules/froala-editor/css/froala_editor.pkgd.min.css'));
app.use('/froalajs',express.static(__dirname+'/node_modules/froala-editor/js/froala_editor.pkgd.min.js'));

// Define routes 
app.get('/',(req,res)=>{
 res.render('editor');
});

var port = process.env.PORT || 3000;
app.listen(port,()=>console.log('server run at port '+port));

Init Froala Editor

Create a new directory called “views”. Inside it, create a new file called “editor.ejs” with the following code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="/froalacss">
    <script src="/froalajs"></script>
    <title>Document</title>
</head>
<body>
    <h1>Froala Editor</h1>
    <textarea id="example"></textarea>
    <script>
            var editor = new FroalaEditor("#example");
     </script>
</body>
</html>

Run your node.js App

node app.js

Open http://localhost:3000\ in your browser, your app should be running and you should be able to see and play with the Froala Editor.

If you feel you missed something or need more explanation refer to the “using the Froala editor in the Node.JS server using Express Framework” tutorial.

Integrate Gemini With Froala

The idea is we will create a custom Froala plugin that will introduce custom Froala buttons. Once the new custom button is clicked it will send a request to the node.js server with a custom AI prompt, the server should handle the request by making a Gemini API call and return a response with the returned output from the Gemini API call. The Froala custom plugin will display the server response, which is the text generated by Gemini API, after making any needed modifications.

Install Dependencies

First, we will need to install the following packages:

  • Install the GoogleGenerativeAI package for Node.js
  • Install dotenv package so we can access the Gemini API key from the .env file. This package will make the .env variables accessible through process.env.
  • Install the marked package. We will use it to convert Gemini API response from mark-down syntax to HTML code.

run

npm install @google/generative-ai dotenv marked

Secure Your API Keys

To keep your Gemini API key safe, create a new .env file at the root directory and add your API key to it

GEMINI_API_KEY=***

Replace *** with your API key value.

Initialize the generative model

Open app.js and add

require('dotenv').config();
const marked = require('marked');

const { GoogleGenerativeAI } = require("@google/generative-ai");

// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);

// For text-only input, use the gemini-pro model
const model = genAI.getGenerativeModel({ model: "gemini-pro"});

In the above code, we initialized the generative model for the Gemini API using the GoogleGenerativeAI package and accessed the API key securely from the .env file. We are using the “gemini-pro” model which allows text-only input. You can specify another model based on your use case.

Define Route to Generate Text From Text-only Prompt Using Gemini API

Define a POST route to handle user prompts using Gemini API and return the AI-generated text.

// Middleware to parse JSON bodies
app.use(express.json());

// Define the /gemini POST route
app.post('/gemini', async (req, res) => {

    // Extract the prompt variable from the request body
    const { prompt } = req.body;
    
    try {
    
        const result = await model.generateContent(prompt);
        
        const response = await result.response;
        
        const responseText = marked.parse(response.text());
    
        // Send the response back to the client
        res.json({ response: responseText });

    } catch (error) {
        // Handle any errors that occur during the API call
        res.status(500).json({ error: error.message });
    }
});

In the above code, the route extracts the prompt from the request body, generates content using the Gemini model, and sends the generated text back to the client after converting it from markdown syntax to HTML. Any errors that occur during the API call are handled appropriately.

Build Froala Custom Plugin for Gemini

Basic Structure

Froala custom plugin is a custom JavaScript function that is added to FroalaEditor.PLUGINS object. Usually, it is defined inside a self-executed function that takes FroalaEditor object as a parameter. The starting point for your plugin should be a public method with the name _init(). The plugin should include a public method for sending requests to the server to generate text using AI. This method is an asynchronous function since we should wait for the response from Gemini API.

        (function (FroalaEditor) {
            // Define the plugin.
            // The editor parameter is the current instance.
            FroalaEditor.PLUGINS.Gemini = function (editor) {


                async function generateText(prompt) {
                    const response = await fetch('/gemini', {
                        method: 'POST',
                        headers: {
                        'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ prompt }),
                    });

                    return await response.json();
                    
                }

                
                // The start point for your plugin.
                function _init () {}

 
                return {
                _init: _init,
                generateText
                }
            }
            })(FroalaEditor);

Custom Froala popup

Now we need a custom popup that will contain an input for users to enter their prompts and display the AI response.

Gemini AI integrated with Froala editor

Asking Gemini and generating response

Displaying Gemini response in Froala editor

Also, it will contain a button to ask AI to give SEO feedback about the content in the editor.

Generating SEO feedback about the content inside the Froala editor

AI-feedback

The custom popup requires the following:

  • Define the popup structure/template.
    • This will contain a div for displaying the chat and an input to enter the user prompt
    • // Load popup template.
      var template = {
          buttons: popup_buttons,
          custom_layer: `<div id="chat-container"></div>
          <div id="chat-form">
            <input id="chat-form-input" type="text" placeholder="Ask AI" />
            <button id="chat-form-button" type="button">Send!</button> 
          </div>
        `
      };
  • initPopup method for creating the popup
  •                 // Create custom popup.
                    function initPopup () {
                        // Load popup template.
                        var template = FroalaEditor.POPUP_TEMPLATES.Geminipopup;
                        if (typeof template == 'function') template = template.apply(editor);
    
                        // Popup buttons.
                        var popup_buttons = '';
    
                        // Create the list of buttons.
                        if (editor.opts.geminiPopupButtons.length > 1) {
                        popup_buttons += '<div class="fr-buttons">';
                        popup_buttons += editor.button.buildList(editor.opts.geminiPopupButtons);
                        popup_buttons += '</div>';
                        }
    
                        // Load popup template.
                        var template = {
                            buttons: popup_buttons,
                            custom_layer: `<div id="chat-container"></div>
                            <div id="chat-form">
                                <input id="chat-form-input" type="text" placeholder="Ask AI" />
                                <button id="chat-form-button" type="button">Send!</button> 
                            </div>
                            `
                        };
    
                        // Create popup.
                        var $popup = editor.popups.create('Gemini.popup', template);
    
                        return $popup;
                    }
  • showPopup method for displaying the popup
  •                 // Show the popup
                    function showPopup () {
                        // Get the popup object defined above.
                        var $popup = editor.popups.get('Gemini.popup');
    
                        // If popup doesn't exist then create it.
                        // To improve performance it is best to create the popup when it is first needed
                        // and not when the editor is initialized.
                        if (!$popup) $popup = initPopup();
    
                        // Set the editor toolbar as the popup's container.
                        editor.popups.setContainer('Gemini.popup', editor.$tb);
    
                        // This custom popup is opened by pressing a button from the editor's toolbar.
                        // Get the button's object in order to place the popup relative to it.
                        var $btn = editor.$tb.find('.fr-command[data-cmd="AI"]');
    
                        // Compute the popup's position.
                        var left = $btn.offset().left + $btn.outerWidth() / 2;
                        var top = $btn.offset().top + (editor.opts.toolbarBottom ? 10 : $btn.outerHeight() - 10);
    
                        // Show the custom popup.
                        // The button's outerHeight is required in case the popup needs to be displayed above it.
                        editor.popups.show('Gemini.popup', left, top, $btn.outerHeight());
                    }
    • Inside showPopup method, we need to register a click event handler for the “Send prompt” button
    • const chatButton = document.getElementById("chat-form-button");
      chatButton.addEventListener('click', _chatButtonHandler);
      

      The private method, _chatButtonHandler, handles the button click event by displaying the user prompt in the chat area and sending it to the Gemini API to show the response. A loading message will be displayed while waiting for the server response to keep the user informed. Implementing a validation process for user input is essential for app security, but it will be left for you to implement.

    •                 function _chatButtonHandler () {
                          const prompt = document.getElementById("chat-form-input").value;
                              editor.Gemini.displayPrompet(prompt);
      
                              editor.Gemini.loadingMessage();
      
                              editor.Gemini.generateText(prompt).then(result => {
      
                              editor.Gemini.displayAiResponse(result);
      
                              }).catch(error => {
                                  // Handle any errors here
                                  console.error('Error:', error);
                              });                    
                      }
    • Add a public method for displaying the loading message
    •                 // Display a loading message
                      function loadingMessage(){
      
                          const chatContainer = document.getElementById("chat-container");
                          const loadingMessage = document.createElement('p');
                          loadingMessage.id = 'chat-loading-response';
                          loadingMessage.textContent = 'Generating response... Please wait.';
                          chatContainer.append(loadingMessage);
      
                      }

      Add a public method for displaying user prompts in the chat area

    •                // Display prompt
                      function displayPrompet(prompt){
      
                          const chatContainer = document.getElementById("chat-container");
                          const loadingMessage = document.createElement('p');
                          loadingMessage.className = 'chat-prompt';
                          loadingMessage.textContent = prompt;
                          chatContainer.append(loadingMessage);
      
                      }

      Add a public method for displaying the response from Gemini AI in the chat area

    •                 function displayAiResponse(result){
                          const chatContainer = document.getElementById("chat-container");
                          const loadingMessage = document.getElementById('chat-loading-response');
      
                          // Remove the loading message
                          chatContainer.removeChild(loadingMessage);
      
                          // Create a new paragraph element for the response
                          const p = document.createElement('p');
                          p.className = 'chat-ai-response';
                          // Set the text content to the resolved data
                          p.innerHTML = result.response; 
      
                          // Prepend the new paragraph to the chat container
                          chatContainer.append(p);
                      }
  • hidePopup method to hide the popup
  •                 // Hide the custom popup.
                    function hidePopup () {
                        document.getElementById("chat-form-button").removeEventListener('click',_chatButtonHandler);
                        editor.popups.hide('Gemini.popup');
                    }
  • A custom Froala button for opening the popup
                // Define an icon and command for the button that opens the custom popup.
                FroalaEditor.DefineIcon('AI', {NAME: 'AI', template: 'text'});            
                FroalaEditor.RegisterCommand('AI', {
                title: 'Display Gemini AI Popup',
                icon: 'AI',
                undo: false,
                focus: false,
                popup: true,
                // Buttons which are included in the editor toolbar should have the plugin property set.
                plugin: 'Gemini',
                callback: function () {
                    if (!this.popups.isVisible('Gemini.popup')) {
                    this.Gemini.showPopup();
                    }
                    else {
                    if (this.$el.find('.fr-marker')) {
                        this.events.disableBlur();
                        this.selection.restore();
                    }
                    this.popups.hide('Gemini.popup');
                    }
                }
                });
  • Custom buttons will appear on the popup
    • Define a custom button for closing the popup
    •             FroalaEditor.DefineIcon('hideAI', { NAME: 'close', SVG_KEY: 'close'});
                  FroalaEditor.RegisterCommand('hideAI', {
                  title: 'Close',
                  icon: 'hideAI',
                  undo: false,
                  focus: false,
                  callback: function () {
                      this.Gemini.hidePopup();
                  }
                  });
    • Define a custom button for clearing the chat area
    •             FroalaEditor.DefineIcon('clearChat', { NAME: 'clear', SVG_KEY: 'remove'})
                  FroalaEditor.RegisterCommand('clearChat', {
                      title: 'Start A New Chat',
                      icon: 'clearChat',
                      undo: false,
                      focus: false,
                      callback: function () {
                      
                          this.Gemini.clearChat();
                      }
                  });
      • the clearChat public method
      • function clearChat(){
            const chatContainer = document.getElementById("chat-container");
           // Prepend the new paragraph to the chat container
           chatContainer.textContent="";
        }
    • Define a custom button for using Gemini to generate feedback about editor content
    •             // Define custom popup 1.
                  FroalaEditor.DefineIcon('getFeedback', { NAME: 'star', SVG_KEY: 'star'})
                  FroalaEditor.RegisterCommand('getFeedback', {
                  title: 'Get Feedback on Your Writing',
                  icon: 'getFeedback',
                  undo: false,
                  focus: false,
                  callback: function () {
      
                      const editorTextContent = this.$el[0].textContent;
                      const proPrompt = "Hello AI, could you please provide SEO feedback on my writing? I am looking for insights on keyword optimization, readability, and meta description effectiveness. Here is the text:"+editorTextContent+". Thank you!"
                      
                      this.Gemini.displayPrompet("Generate feedback about my writing (editor content)");
      
                      this.Gemini.loadingMessage();
      
                      this.Gemini.generateText(proPrompt).then(result => {
      
                              this.Gemini.displayAiResponse(result);
      
                          }).catch(error => {
                              // Handle any errors here
                              console.error('Error:', error);
                          });
                      }
                  });

      In the above code, we defined a custom button for requesting AI feedback on editor content. It retrieves the editor’s text content and creates a prompt for the AI to generate feedback on SEO aspects. The AI is asked to provide insights on keyword optimization, readability, and meta-description effectiveness. The `generateText` method is called with the generated prompt, and upon receiving the result, the displayAiResponse function is invoked to show the AI’s feedback in the chat area. Any errors encountered during this process are logged.

  • styling the popup
  • <style>
            #chat-container{
                width: 600px;
                overflow: scroll;
                height: 300px;
    
            }
            #chat-form{
                padding: 15px;
            }
            #chat-form-input{
                width: 80%;
                padding: 10px;
                border-radius: 5px;
                border: 1px solid #999;
            }
    
            #chat-form-button{
                padding: 10px;
                background: #1978de;
                color: #fff;
                border: 1px solid;
                border-radius: 6px;
                cursor: pointer;
            }
    
            #chat-form-button:hover{
                background: #065cb8;
    
            }
            .chat-prompt, .chat-ai-response{
                padding: 15px;
                text-align: justify;
            }
    
            .chat-prompt{
                background: #eee;
                width: auto;
                padding: 10px;
                margin: 15px 100px 0 0;
                border-radius: 15px;
                border-top-left-radius: 0;
            }
    
        </style>

Combining all the code creates the Gemini plugin script

     <script>
        (function (FroalaEditor) {

            // Define popup template.
            Object.assign(FroalaEditor.POPUP_TEMPLATES, {
            'Gemini.popup': '[_BUTTONS_][_CUSTOM_LAYER_]'
            });

            // Define popup buttons.
            Object.assign(FroalaEditor.DEFAULTS, {
                geminiPopupButtons: ['hideAI', '|', 'getFeedback','clearChat'],
            });

            // Define the plugin.
            // The editor parameter is the current instance.
            FroalaEditor.PLUGINS.Gemini = function (editor) {

                // Create custom popup.
                function initPopup () {
                    // Load popup template.
                    var template = FroalaEditor.POPUP_TEMPLATES.Geminipopup;
                    if (typeof template == 'function') template = template.apply(editor);

                    // Popup buttons.
                    var popup_buttons = '';

                    // Create the list of buttons.
                    if (editor.opts.geminiPopupButtons.length > 1) {
                    popup_buttons += '<div class="fr-buttons">';
                    popup_buttons += editor.button.buildList(editor.opts.geminiPopupButtons);
                    popup_buttons += '</div>';
                    }

                    // Load popup template.
                    var template = {
                        buttons: popup_buttons,
                        custom_layer: `<div id="chat-container"></div>
                        <div id="chat-form">
                            <input id="chat-form-input" type="text" placeholder="Ask AI" />
                            <button id="chat-form-button" type="button">Send!</button> 
                        </div>
                        `
                    };

                    // Create popup.
                    var $popup = editor.popups.create('Gemini.popup', template);

                    return $popup;
                }

                function _chatButtonHandler () {
                    const prompt = document.getElementById("chat-form-input").value;
                        editor.Gemini.displayPrompet(prompt);

                        editor.Gemini.loadingMessage();

                        editor.Gemini.generateText(prompt).then(result => {

                        editor.Gemini.displayAiResponse(result);

                        }).catch(error => {
                            // Handle any errors here
                            console.error('Error:', error);
                        });                    
                }
                                
                // Show the popup
                function showPopup () {
                    // Get the popup object defined above.
                    var $popup = editor.popups.get('Gemini.popup');

                    // If popup doesn't exist then create it.
                    // To improve performance it is best to create the popup when it is first needed
                    // and not when the editor is initialized.
                    if (!$popup) $popup = initPopup();

                    // Set the editor toolbar as the popup's container.
                    editor.popups.setContainer('Gemini.popup', editor.$tb);

                    // This custom popup is opened by pressing a button from the editor's toolbar.
                    // Get the button's object in order to place the popup relative to it.
                    var $btn = editor.$tb.find('.fr-command[data-cmd="AI"]');

                    // Compute the popup's position.
                    var left = $btn.offset().left + $btn.outerWidth() / 2;
                    var top = $btn.offset().top + (editor.opts.toolbarBottom ? 10 : $btn.outerHeight() - 10);

                    const chatButton = document.getElementById("chat-form-button");
                    chatButton.addEventListener('click', _chatButtonHandler);

                    // Show the custom popup.
                    // The button's outerHeight is required in case the popup needs to be displayed above it.
                    editor.popups.show('Gemini.popup', left, top, $btn.outerHeight());
                }

                // Hide the custom popup.
                function hidePopup () {
                    document.getElementById("chat-form-button").removeEventListener('click',_chatButtonHandler);
                    editor.popups.hide('Gemini.popup');
                }

                async function generateText(prompt) {
                    const response = await fetch('/gemini', {
                        method: 'POST',
                        headers: {
                        'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ prompt }),
                    });

                    return await response.json();
                    
                }

                // Display a loading message
                function loadingMessage(){

                    const chatContainer = document.getElementById("chat-container");
                    const loadingMessage = document.createElement('p');
                    loadingMessage.id = 'chat-loading-response';
                    loadingMessage.textContent = 'Generating response... Please wait.';
                    chatContainer.append(loadingMessage);

                }

                // Display prompt
                function displayPrompet(prompt){

                    const chatContainer = document.getElementById("chat-container");
                    const loadingMessage = document.createElement('p');
                    loadingMessage.className = 'chat-prompt';
                    loadingMessage.textContent = prompt;
                    chatContainer.append(loadingMessage);

                }

                function displayAiResponse(result){
                    const chatContainer = document.getElementById("chat-container");
                    const loadingMessage = document.getElementById('chat-loading-response');

                    // Remove the loading message
                    chatContainer.removeChild(loadingMessage);

                    // Create a new paragraph element for the response
                    const p = document.createElement('p');
                    p.className = 'chat-ai-response';
                    // Set the text content to the resolved data
                    p.innerHTML = result.response; 

                    // Prepend the new paragraph to the chat container
                    chatContainer.append(p);
                }

                function clearChat(){
                    const chatContainer = document.getElementById("chat-container");

                    // Prepend the new paragraph to the chat container
                    chatContainer.textContent="";
                }

                // The start point for your plugin.
                function _init () {}

 
                return {
                _init: _init,
                generateText,
                loadingMessage,
                displayPrompet,
                displayAiResponse,
                clearChat,
                showPopup,
                hidePopup
                }
            }


            // Define an icon and command for the button that opens the custom popup.
            FroalaEditor.DefineIcon('AI', {NAME: 'AI', template: 'text'});            
            FroalaEditor.RegisterCommand('AI', {
            title: 'Display Gemini AI Popup',
            icon: 'AI',
            undo: false,
            focus: false,
            popup: true,
            // Buttons which are included in the editor toolbar should have the plugin property set.
            plugin: 'Gemini',
            callback: function () {
                if (!this.popups.isVisible('Gemini.popup')) {
                this.Gemini.showPopup();
                }
                else {
                if (this.$el.find('.fr-marker')) {
                    this.events.disableBlur();
                    this.selection.restore();
                }
                this.popups.hide('Gemini.popup');
                }
            }
            });

            // Define custom popup close button icon and command.
            FroalaEditor.DefineIcon('hideAI', { NAME: 'close', SVG_KEY: 'close'});
            FroalaEditor.RegisterCommand('hideAI', {
            title: 'Close',
            icon: 'hideAI',
            undo: false,
            focus: false,
            callback: function () {
                this.Gemini.hidePopup();
            }
            });

            
            // Define custom popup 1.
            FroalaEditor.DefineIcon('getFeedback', { NAME: 'star', SVG_KEY: 'star'})
            FroalaEditor.RegisterCommand('getFeedback', {
            title: 'Get Feedback on Your Writing',
            icon: 'getFeedback',
            undo: false,
            focus: false,
            callback: function () {

                const editorTextContent = this.$el[0].textContent;
                const proPrompt = "Hello AI, could you please provide SEO feedback on my writing? I am looking for insights on keyword optimization, readability, and meta description effectiveness. Here is the text:"+editorTextContent+". Thank you!"
                
                this.Gemini.displayPrompet("Generate feedback about my writing (editor content)");

                this.Gemini.loadingMessage();

                this.Gemini.generateText(proPrompt).then(result => {

                        this.Gemini.displayAiResponse(result);

                    }).catch(error => {
                        // Handle any errors here
                        console.error('Error:', error);
                    });
                }
            });

            // clear chat button
            FroalaEditor.DefineIcon('clearChat', { NAME: 'clear', SVG_KEY: 'remove'})
            FroalaEditor.RegisterCommand('clearChat', {
                title: 'Start A New Chat',
                icon: 'clearChat',
                undo: false,
                focus: false,
                callback: function () {
                
                    this.Gemini.clearChat();
                }
            });
            
    })(FroalaEditor);
     </script>

Customize Froala Editor to Use Gemini Plugin

Finally, edit the Froala toolbar to display the new Gemini dropdown button.

    <script>

        var editor = new FroalaEditor("#example",{
            toolbarButtons: [['AI', 'bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript'], ['fontFamily', 'fontSize', 'textColor', 'backgroundColor'], ['inlineClass', 'inlineStyle', 'clearFormatting']]

        });

    </script>

Now once you run the application again, you should see the “AI” button on the toolbar. By clicking the “AI” button, you can display the Gemini AI popup. The popup allows you to interact with the Gemini plugin, enabling users to prompt Gemini to get responses and generate feedback on their writing.

Similarly, you can code new custom buttons to add more AI functions within the Froala editor. These custom functionalities enhance the Froala Editor’s capabilities and provide a seamless user experience for content creation and editing.

Get The Application Code

We made this tutorial code available for free download from this GitHub repo. This way you can quickly implement these features, customize them to your needs, and improve your content creation workflows.

If you would like a tutorial on using the “gemini-pro-vision” model for generating text from text and image inputs (multimodal mode), please leave a comment.

Unleash the Power of AI in Your Froala Editor

Incorporating Gemini AI into your Froala Editor is not just an enhancement—it’s a transformation. By enabling AI-powered features like chat interfaces and instant feedback within your editor, you equip your users with the tools to elevate their content creation process, making it more efficient, engaging, and error-free. Don’t let your application lag behind in harnessing the capabilities of AI.

Take action today! Start by purchasing Froala and integrate the Gemini AI with your Froala Editor to see immediate improvements in user engagement and content quality. Enhance your product, empower your users, and lead the way in innovative content creation.

Utilizing Froala HTML editor software in Angular standalone component with SSR disabled

HTML editor software

Angular 17 gives preference to standalone components in new projects. This streamlines development by eliminating the requirement for NgModules and advocates for a cleaner, modular code design.

In this guide, we will demonstrate how to integrate the Froala WYSIWYG editor within a standalone Angular component, particularly when Server-Side Rendering (SSR) is disabled. The Froala editor is known for its rich text capabilities and user-friendly interface, making it perfect for applications needing powerful content management abilities. By integrating Froala, developers can provide users with a robust editing tool that improves the functionality and user experience of web applications.

HTML editor software with Angular

Start Developing Your Angular App

For those who are fresh, make sure you have Angular CLI installed. The Angular CLI is a tool on the command line that allows you to initialize and manage Angular projects right from the terminal.

If it is not installed, run this command:

npm install -g @angular/cli

Now you can run “ng” commands in your terminal.

Run the following command to create a new Angular app:

ng new froala-standalone-app

This will prompt you with the following

  1. Which stylesheet format would you like to use? (CSS/SCSS/Sass/Less)
    Select your preferred format.
  2. Do you want to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)? (y/N)
    It inquires if you would like to configure your application to render pages on the server side and create static HTML files for your pages while building. Type “N” to turn off SSR.
    Enabling SSR and SSG means that your Angular app will be more performant and SEO-friendly, but it also implies a different build and deployment process, as you’ll need to handle the server-side and static aspects of your application. We will not cover this in this tutorial.

install new Angular app

After completing the prompts, an Angular project structure will be created in a new folder called “froala-standalone-app”. Navigate into the project directory using

cd froala-standalone-app

As of Angular 17, using the “ng new” command generates standalone components as the default. No longer will an “app.module.ts” exist.

Open the folder in your IDE. The project structure is as follows:

Angular 17 folder stracture

In the “src” folder, you will find the “index.html” file and the default component “app”.

Angular 17 app component

Integrate Froala With a Standalone Angular App

Let’s create another component with the name “wysiwyg“ to use for integrating the Froala editor into your application:

ng generate component wysiwyg

create a new Angular component

The command above will create a new folder, “wysiwyg”, inside the “src/app” directory. This folder will contain the following files for the “wysiwyg” component:

  • wysiwyg.component.css
  • wysiwyg.component.html
  • wysiwyg.component.spec.ts
  • wysiwyg.component.ts

Froala HTML editor software inside Augular standalone component

Install the Froala Angular SDK

let’s install the Froala Angular rich-text editor into your Angular application. The Froala Angular SDK includes the essential tools and components to easily integrate the functionality of the Froala editor software into your standalone Angular components.

npm install angular-froala-wysiwyg

install Froala Angular SDK

Once the installation is complete, the “angular-froala-wysiwyg” will appear in the “dependencies” section of the package.json file.

Styling the Froala Editor

Ensure that Froala’s style resources are included in your standalone Angular application. In angular.json, add Froala stylesheets under the “styles“ array.

"styles": [

"src/styles.css",

"node_modules/froala-editor/css/froala_editor.pkgd.min.css",

"node_modules/froala-editor/css/froala_style.min.css"

],

The “froala_editor.pkgd.min.css“ includes the styles for the core editor and all Froala plugins.

The “froala_style.min.css“ includes the styles needed for displaying the content created by the editor outside the editor.

Setting Up The Froala Component

Open the “wysiwyg.component.ts“ and import the FroalaEditorModule and FroalaViewModule components and add them to the “imports“ array

import { Component } from '@angular/core';
import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';

@Component({
  selector: 'app-wysiwyg',
  standalone: true,
  imports: [FroalaEditorModule, FroalaViewModule],
  templateUrl: './wysiwyg.component.html',
  styleUrl: './wysiwyg.component.css'
})
export class WysiwygComponent {

}

Navigate to “wysiwyg.component.html” and add

<div [froalaEditor]>Hello, Froala!</div>

Now we can use “wysiwyg“ component to display the Froala editor in any other component in your Angular application.

Displaying Froala on the main page

Let’s add “wysiwyg“ component to the “app” component to display Froala on the main page.

Open “app.component.ts“ and import WysiwygComponent

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';

import { WysiwygComponent } from './wysiwyg/wysiwyg.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet, WysiwygComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'froala-standalone-app';
}

Open “app.component.html“ and add the following code to include the “wysiwyg” component:

<app-wysiwyg></app-wysiwyg>

This code will render the Froala editor on the main page of your Angular application.

Start your App

Next, you can serve the app by running `ng serve`. This command compiles the application and serves it locally, typically on `http://localhost:4200/`. You can now access your Angular app in a web browser to see the initial application setup.

The editor will be displayed on the homepage.

Display Froala WYSIWYG editor inside Angular standalone component

Including Froala Plugins

You may notice that Froala is displayed with just its basic features. That’s because we haven’t included the plugin’s JavaScript files. Open the “wysiwyg.component.ts“ and add

import 'froala-editor/js/plugins.pkgd.min.js';

This will include all Froala default plugins. Return to `http://localhost:4200/`, you will find the full-featured editor is loaded.

Full-featured WYSIWYG editor in Angular 17

If you are using just a few features, you can include the JavaScript files for the required plugins instead of “plugins.pkgd.min.js”. For example:

// import 'froala-editor/js/plugins.pkgd.min.js';

// Import plugins one by one

import 'froala-editor/js/plugins/align.min.js';

import 'froala-editor/js/plugins/image.min.js';

Customizing the Editor Options, Initial Content, and Setup Events

By adjusting the options, setting the initial content, and defining event handlers, you can create a unique and personalized editing experience for your users based on your specific requirements.

Inside the “WysiwygComponent“ class, define:

  • A string with the editor’s initial HTML content
  • An array containing the customized options, including the “events” option where you can set your editor events handlers.
import { Component } from '@angular/core';
import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';
// import 'froala-editor/js/plugins.pkgd.min.js';
// Import plugins one by one
import 'froala-editor/js/plugins/align.min.js';
import 'froala-editor/js/plugins/image.min.js';

@Component({
  selector: 'app-wysiwyg',
  standalone: true,
  imports: [FroalaEditorModule, FroalaViewModule],
  templateUrl: './wysiwyg.component.html',
  styleUrl: './wysiwyg.component.css'
})
export class WysiwygComponent {
  
  editorContent = 'Learn more about <a href="https://froala.com/angular-rich-text-editor/">Froala Angular WYSIWYG Editor</a>';
  
  public options: Object = {

    toolbarButtons: ['alignRight', 'bold', 'insertImage'],

    events: {
      'froalaEditor.contentChanged': function () {
        console.log('Content updated!');
      },
    },
  };
  
}

Then, open “app.component.html“ and modify it

<div [froalaEditor]="options" [(froalaModel)]="editorContent"></div>

Now the editor should look like

Froala HTML editor software inside Angular 17

Using the editor instance from the callback arguments, you can call editor methods as described in the method docs.

Using the editor content outside the editor

To display the editor content in other elements in your application, you can utilize the froalaView component and the variable you have passed to the froalaModel attribute of the froalaEditor component. Open the “app.component.html“ file and modify it to

<p>wysiwyg works!</p>

<div [froalaEditor]="options" [(froalaModel)]="editorContent"></div>

<h2>Preview the editor content </h2>

<hr>

<div [froalaView]="editorContent"></div>

Now open your homepage, start editing the editor content, and notice your changes appear outside it too.

two-way binding between Froala and Angular

Conclusion

By integrating the Froala HTML editor software in the Angular standalone component using the Angular Froala SDK, you can enhance the editing experience and functionality in your application.

In this article, we explored how to integrate the Froala editor into a standalone Angular component while Server-Side Rendering is disabled. By following our step-by-step guide, you learned how to create a new Angular app, set up the Froala Angular rich-text editor, customize editor options, and display editor content outside the editor.

Now that you have the tools to enhance your Angular application with the Froala editor, why not give it a try? Start creating dynamic and interactive content for your users today by incorporating this powerful editor into your projects. Happy coding!

 

Simple Integration Guide: Adding Math Equations and Chemistry Formulas to Froala Editor

integrating Froala with mathType

Wondering how to type math equations and chemistry formulas in Froala Editor?

By integrating Froala with MathType, you can easily insert math equations and chemistry formulas in the Froala editor. In this blog post, we will learn how to integrate Froala and mathType.

What is MathType?

MathType is an intuitive solution for creating quality math formulas in your documents and digital content. It is the leading formula editor and equation writer used by K-12 and university STEM students and faculty worldwide.

MathType has a user-friendly interface that makes writing scientific content on your computer fun. Forget about having to learn LaTeX to write math on a computer.

MathType has a handwriting interface powered with AI to convert your handwritten formula into a clean digital equation ready to be used in the editor.

MathType is not just for math equations but also provides a tool for handling chemistry formulas.

MathType is designed to meet accessibility standards in order to make the software accessible to individuals with disabilities. It follows the WCAG 2.0 guidelines from W3C, making sure content can be read by assistive technologies and operated with a keyboard.

Incorporating Froala HTML editor includes MathType capabilities, enabling easy writing of math equations and chemical formulas in your WYSIWYG editor.

How Can I Integrate MathType With Froala?

  • include Froala stylesheet and scripts files and the element you want to initialize the editor in your HTML page
<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0" />
        // Froala Stylesheet
        <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />
    </head>

    <body>
        <!-- HTML element for displaying the editor -->
        <div id="editor"></div>
        <!-- Froala JS file -->
        <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>  

    </body>

</html>
  • Install the MathType for Froala npm module by running the following command:
npm i @wiris/mathtype-froala3
  •  Include the MathType-Froala plugin script in your HTML page
<script src="node_modules/@wiris/mathtype-froala3/wiris.js"></script>
  • Initialize the editor
new FroalaEditor('#editor', {
   // Add MathType and ChemType buttons to the toolbar and the image menu:
   toolbarButtons: ['wirisEditor', 'wirisChemistry'], 
   quickInsertButtons: ['image', 'table', 'wirisEditor', 'wirisChemistry'],
   // Allow all tags, in order to allow MathML:
   htmlAllowedTags:  ['.*'],
   htmlAllowedAttrs: ['.*'],
   // Allow empty tags on these next elements for proper formula rendering:
   htmlAllowedEmptyTags: ['mprescripts', 'none', 'textarea', 'a', 'iframe', 'object', 'video', 'style', 'script', '.fa', '.fr-emoticon', '.fr-inner', 'path', 'line', 'hr'],
});

In the above code:

  • We customized the editor toolbar buttons to display a button for adding math equations “wirisEditor“ and a button for adding chemistry formulas “wirisChemistry“ using `toolbarButtons` option.
  • We also customized the `quickInsertButtons` option to display the MathType buttons on the Quick Insert toolbar. This toolbar appears when you have the cursor on a blank new line.
  • Additionally, we set the `htmlAllowedTags`, `htmlAllowedAttrs`, and `htmlAllowedEmptyTags` properties to ensure proper rendering of formulas in the editor and while displaying it later on the HTML page outside the editor.
    • htmlAllowedTags is an array containing allowed tags to be inserted in the editor, by default it’s set to
      ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre', 'progress', 'queue', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'style', 'section', 'select', 'small', 'source', 'span', 'strike', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr']

      Since MathType uses other HTML tags, we customized htmlAllowedTags to be

      htmlAllowedTags:  ['.*'],

      This allows MathType custom tags to be inserted in the editor.

    • htmlAllowedAttrs is an array containing allowed attributes to be used for tags, by default it’s set to
      ['accept', 'accept-charset', 'accesskey', 'action', 'align', 'allowfullscreen', 'allowtransparency', 'alt', 'aria-.*', 'async', 'autocomplete', 'autofocus', 'autoplay', 'autosave', 'background', 'bgcolor', 'border', 'charset', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'color', 'cols', 'colspan', 'content', 'contenteditable', 'contextmenu', 'controls', 'coords', 'data', 'data-.*', 'datetime', 'default', 'defer', 'dir', 'dirname', 'disabled', 'download', 'draggable', 'dropzone', 'enctype', 'for', 'form', 'formaction', 'frameborder', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'http-equiv', 'icon', 'id', 'ismap', 'itemprop', 'keytype', 'kind', 'label', 'lang', 'language', 'list', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'mozallowfullscreen', 'multiple', 'muted', 'name', 'novalidate', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'reversed', 'rows', 'rowspan', 'sandbox', 'scope', 'scoped', 'scrolling', 'seamless', 'selected', 'shape', 'size', 'sizes', 'span', 'src', 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'summary', 'spellcheck', 'style', 'tabindex', 'target', 'title', 'type', 'translate', 'usemap', 'value', 'valign', 'webkitallowfullscreen', 'width', 'wrap']

      Since MathType uses other HTML attributes, we customized htmlAllowedAttrs to be

      htmlAllowedAttrs: ['.*'],
    • htmlAllowedEmptyTags is an array containing a list of tags that are not removed when they have no content inside. We have added ‘mprescripts’ and ‘none’ tags since these tags can be inserted by MathType and could be empty.

Customize MathType Editor

MathType offers various choices for adjusting its design, enabling you to coordinate it with your application’s interface and enhance the user’s experience. Refer to the MathType documentation for a comprehensive list of available choices. Use the mathTypeParameters option to send these parameters. One way to adjust the MathEditor language is by following this process.

mathTypeParameters: { 
 editorParameters: { Language: 'es' },
},

You can also disable the handwriting interface by setting the detectHand option to false.

mathTypeParameters: { 
 editorParameters: { Language: 'es' },
       detectHand: false
},

Here is the full page code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />
    <title>Froala & MathType integration</title>
</head>

<body>
    <!-- HTML element fo displaying the editor -->
    <div id="editor"></div>

    <!-- Froala JS file -->
    <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>  

    <script src="node_modules/@wiris/mathtype-froala3/wiris.js"></script>

    <script>
        new FroalaEditor('#editor', {
            // Add MathType and ChemType buttons to the toolbar and the image menu:
            toolbarButtons: ['wirisEditor', 'wirisChemistry'], 
            quickInsertButtons: ['image', 'table', 'wirisEditor', 'wirisChemistry'],
            // Allow all tags, in order to allow MathML:
            htmlAllowedTags:  ['.*'],
            htmlAllowedAttrs: ['.*'],
            // Allow empty tags on these next elements for proper formula rendering:
            htmlAllowedEmptyTags: ['mprescripts', 'none', 'textarea', 'a', 'iframe', 'object', 'video', 'style', 'script', '.fa', '.fr-emoticon', '.fr-inner', 'path', 'line', 'hr'],
            //mathType options
            mathTypeParameters: { 
                editorParameters: { 
                    Language: 'es',
                    backgroundColor: '#333',
                    detectHand: false
                 },
            },
        });
    </script>
</body>
</html>

How Can I Render MathML Data and Store Generated Images Locally?

The MathType npm package uses remotely hosted services to display MathML content remotely. Nevertheless, we suggest that you set up these services on your backend. This will enable you to, among other capabilities, set up the service and save the images produced by MathType on your server.

Plugins are available for Java, PHP, .NET, and Ruby on Rails. If you are using any of these technologies, make sure to get the plugin for your backend technology from here.

How To Display Math Equations and Chemistry Formulas Outside The Editor?

To display mathematical formulas on the webpage where content produced by the Froala HTML editor will be visible, the target page needs to include the MathType script. For example, for the default setting, this would be:

<script src="https://www.wiris.net/demo/plugins/app/WIRISplugins.js?viewer=image"></script>

How To Insert Math Equations and Chemistry Formulas Effortlessly?

Once you integrate MathType, there will be two icons added to the Froala toolbar.

Integrate Froala and MathType editor

Clicking on the square root icon will display all the symbols available for math equations. Once you are done, click on the OK button. The equation will be inserted into your WYSIWYG editor.
MathType editor

Clicking on the C icon will display all the symbols available for chemistry formulas. Once you are done, click on the OK button. The formula will be inserted into your WYSIWYG editor.
Button to open chemType editor

ChemType editor

Conclusion

To sum up, integrating Froala with MathType provides a seamless solution to include math equations and chemistry formulas in your content creation workflow. By following the instructions provided in this blog post, you can enhance the functionality of Froala Editor, making it easier to create and display complex scientific content. Whether you are a student, educator, or professional in the STEM field, leveraging MathType’s capabilities within Froala Editor can streamline your workflow and improve the accessibility of your mathematical and chemical content. Embracing this integration opens up a world of possibilities for effectively communicating scientific concepts in a visually appealing and interactive manner.

Are you prepared to enhance your content by including flawless math equations and chemistry formulas? Try out the combination of Froala Editor and MathType now to see their powerful capabilities. Begin generating visually impressive and engaging scientific content with ease. Give it a try now and access a higher level of creativity!

Download Froala Editor

Efficient Handling of Special Characters in HTML with Froala WYSIWYG Editor

special characters in HTML pages

Have you ever wondered how developers add cool symbols like copyright signs to websites? It’s all about special characters! This blog post will show you how to use special characters in HTML pages. We’ll explain the differences between Unicode values and HTML entities to represent special characters in a way that’s easy to understand. Plus, we’ll introduce you to the Froala editor, a handy tool that makes working with special characters a breeze.

Get ready to learn the secrets of special characters and level up your web design skills. Let’s make your web pages stand out with special characters that add a touch of magic!

What are Special Characters?

Special characters are characters that are not part of the standard alphanumeric or punctuation characters found on a typical keyboard. These characters serve specific functions or have special meanings in various contexts, such as programming languages, markup languages like HTML, and text processing.

Special characters can include symbols, diacritics, mathematical symbols, currency symbols, punctuation marks, and other characters used for specific purposes. Some common examples of special characters include:

  1. & (ampersand): Used in HTML to start an entity reference.
  2. # (hash or pound sign): Used in programming languages for comments or to indicate numbers.
  3. $ (dollar sign): Used to represent currency or variables in programming.
  4. @ (at sign): Used in email addresses and social media handles.

Special characters can have different meanings and functions depending on the context in which they are used. It is important to handle them correctly using HTML entities or Unicode values to avoid formatting issues or errors in the display of web content.

How to Include Special Characters in HTML?

Special characters in HTML can be handled using HTML entities or Unicode values. Both values are used in HTML to represent special characters that cannot be easily typed on a keyboard or may cause formatting issues if used directly in the code. They are used to display characters such as copyright symbols, arrows, and accented letters on web pages.

Using HTML entities or Unicode values, you can effectively include special characters in HTML and ensure they are displayed correctly on your web pages.

What is the Difference Between HTML Entity and Unicode for Special Characters?

An HTML entity and Unicode are both used to represent special characters in HTML, but they serve different purposes and have different formats.

An HTML entity is a named code that represents a specific character in HTML. For example, &copy; is the HTML entity for the copyright symbol ©. HTML entities begin with an ampersand (&) and end with a semicolon (;). Entities are easier to read and understand in the code, making them more human-friendly.

Unicode, on the other hand, is a universal character encoding standard that assigns a unique numerical value to every character and symbol in almost all the world’s writing systems. Unicode values are typically represented in HTML using the hexadecimal format &#xXXXX; (where XXXX is the Unicode value in hexadecimal). For example, the Unicode value for the copyright symbol © is 00A9, so it can be represented in HTML as &#x00A9;.

In summary, HTML entities are named codes for special characters in HTML, while Unicode provides a universal standard for encoding characters across different writing systems. HTML entities are easier to use and understand in the code, while Unicode allows for a broader range of characters to be represented in a standardized way.

Simplifying Handling HTML special characters in web pages

Developers face challenges in using special characters due to the need for accurate HTML symbol codes, entities, or Unicode values for each character. Mishandling these characters can result in formatting problems or display errors on websites. While there are reference websites available for these codes and values, a more effective solution is to utilize an editor that gives you a dropdown menu for selecting special characters visually. Using a text editor that supports Unicode encoding ensures correct display and saving of characters.

Froala Wysiwyg editor is an example of a powerful editor that supports special characters efficiently by providing a convenient way to select and insert symbols without the need to remember specific codes or values. This editor simplifies the process of incorporating special characters into web content, ensuring accurate display and compatibility across different browsers. By utilizing tools like the Froala Wysiwyg editor, developers can enhance the visual appeal and functionality of their websites with ease.

How does Froala manage special characters?

Froala offers two plugins for managing special characters in the editor.

Special Characters Plugin

The special Characters plugin adds a toolbar button that opens a dropdown menu. This menu contains a list of special characters for users to select from. By utilizing the specialCharactersSets option, you can specify the special characters to be displayed and categorize them. For example, consider the following initialization code:

new FroalaEditor('div#froala-editor', {
  // Set custom buttons.
  toolbarButtons: ['bold', 'italic', 'underline', 'specialCharacters', 'html'],
  specialCharactersSets: [    
  {
      title: "Letters",
      "char": "&Imacr;",
      list: [{
        "char": "&imacr;",
        desc: "LOWERCASE I WITH MACRON"
      }],
    },
    {
      title: "Punctuation",
      "char": "&copy;",
      list: [{
        "char": "&reg;",
        desc: "REGISTERED TRADE MARK SIGN"
      }, {
        "char": "&copy;",
        desc: "COPYRIGHT SIGN"
      }]
    },

  ],
})

In the code above, the editor toolbar was customized with a limited selection of buttons, including the “specialCharacters” button. Two categories of special characters were defined to be displayed when the user clicks on this button using the specialCharactersSets option.

The first category is “Letters,” represented by the uppercase letter I with macron (Ĩ), and includes only one symbol: “the lowercase letter i with macron (ĩ)”. The second category, “Punctuation,” contains two symbols: the copyright © and the registered trademark ® signs.

special characters in Froala editor

Now when using the editor, you can conveniently select and insert the defined special characters without having to remember specific codes or values. This simplifies the process of incorporating special characters into web content, ensuring accurate display and compatibility across different browsers.

However, if you insert the “ĩ” and then switch the editor to the code view mode, you will find that it is still showing as “ĩ” and not converted to the corresponding entity value ”&imacr;”. That’s why the Froala Entities plugin comes in to fix this problem.

Froala special characters plugin

Entities Plugin

The Entities plugin displays HTML entities in the code view when their related special character symbol is inserted in the editor. Use the entities option to specify the HTML entities that should be displayed in the code view when their related special character symbol is inserted in the editor. For instance, using the following initialization code will convert “ĩ” to the corresponding entity value ”&imacr;” in the code view.

new FroalaEditor('div#froala-editor', {

  entities: '&imacr;'

})

The power of using Special Characters and Entities Plugins together

Combining the functionality of the Special Characters and Entities plugins provides a comprehensive solution for handling special characters seamlessly within the Froala Wysiwyg editor. This integration enhances the editing experience and ensures the proper display of special characters in the HTML code.

For example, consider the following initialization code:

new FroalaEditor('div#froala-editor', {
  // Set custom buttons.
  toolbarButtons: ['bold', 'italic', 'underline', 'specialCharacters', 'html'],
  specialCharactersSets: [    
  {
      title: "Letters",
      "char": "&Imacr;",
      list: [{
        "char": "&imacr;",
        desc: "LOWERCASE I WITH MACRON"
      }],
    },
    {
      title: "Punctuation",
      "char": "&copy;",
      list: [{
        "char": "&reg;",
        desc: "REGISTERED TRADE MARK SIGN"
      }, {
        "char": "&copy;",
        desc: "COPYRIGHT SIGN"
      }]
    },

  ],
  entities: '&imacr;&reg;&copy;'
})

Using the above code, the Special Characters plugin will display a popup containing ĩ, ©, and ® symbols. When one of them is selected, the entities plugin converts it to their respective HTML entity – ĩ to “&imacr;“, © to “ &copy;“, and ® to “ &reg;“ in the code view.

Froala Entity Plugin

By combining the Special Characters and Entities Plugins, users no longer need to search for special character entity values every time they want to use one. They can simply select the icon from the dropdown menu.

Conclusion

The Froala WYSIWYG editor with its Special Characters and Entities Plugins streamlines the process of inserting special characters, eliminating the need to memorize specific codes or values. This powerful editor not only enhances the editing experience but also guarantees the proper display of special characters within the HTML code.

By simplifying the handling of special characters, developers can focus on enhancing the visual appeal and functionality of their websites without worrying about formatting issues. The comprehensive solution offered by Froala empowers developers to effortlessly incorporate special characters, adding a touch of magic to their web pages and creating a seamless user experience.

Embrace the power of special characters in your HTML projects by utilizing the Froala WYSIWYG editor with its Special Characters and Entities Plugins. Experience the seamless integration, streamlined workflow, and accurate display of special characters. Try Froala editor today and unleash your creativity in web design!

Download Froala Editor

Best Practices for Text to HTML Editors: Prioritizing Code Quality

Learn to Convert Plain Text to HTML Easily with Froala

Developing engaging content is merely a portion of the challenge in web development. Your message comes to life by delivering that information impactfully on a webpage. However, numerous experts face challenges when transitioning from plain text to HTML with text to html editors.

This guide functions as a directional tool, systematically describing a direct strategy for accomplishing this conversion procedure.

Acquiring a comprehensive understanding of HTML will enable you to utilize a text to HTML editor effectively, converting your written compositions into interactive and visually captivating web content. This transformation allows your content to seamlessly connect with your intended audience, effectively enhancing engagement and retention.

Understanding Plain Text and HTML

Let’s start by learning about the building blocks. Plain text is any unformatted text document. It’s essentially the same as a simple notepad file: pure text with no additional formatting or graphic components. Plain text is fantastic for raw content but cannot define a webpage’s organization, design, or interactivity.

HTML is the foundation for webpages, offering a set of instructions browsers utilize to interpret and display content.  These components instruct the web browser on presenting the content, including formatting such as headings, paragraphs, and bolded text.

Headings are denoted by h1>, paragraphs by p>, and bold text by b>, all typical foundational elements. Utilizing these identifiers enables one to delineate the fundamental arrangement and structure of the content on a webpage.

Why Use a WYSIWYG Editor?

While HTML provides exact control, manual coding can be time-consuming and difficult, particularly for inexperienced people.  Consider crafting lengthy chapters full of arcane tags only to achieve basic formatting. In such situations, WYSIWYG editors emerge as transformative tools.

The intuitive interface of WYSIWYG editors serves as an intermediary between plain text and HTML. An alternative approach to code entry involves using tools, menus, and icons to represent the intended layout visually. Do you need to bold a sentence? Click the “bold” button.

Want to make a bulleted list? Use the list-creation tool.  This eliminates the need to memorize or manually write code, simplifying content development.

Learn to Convert Plain Text to HTML Easily with Froala

Getting Started with Froala

Froala is a strong text to HTML Editor. Froala integrates seamlessly into your web project. Typically, you will include the Froala JavaScript library on your web pages.  This library includes all of the functionality required for the editor to function. 

Alternatively, Froala provides plugins for major frameworks such as WordPress and React, allowing for smooth integration with existing workflows. 

Once set up, Froala gives a toolbar with straightforward buttons and choices, allowing you to format text, add images, and structure your material without writing a single line of code.

HTML offers full control over web page structure and functionality. But, there are obvious benefits to using a text-to-HTML editor like Froala:

Markdown Plugin

Froala has a powerful Markdown plugin, which expands the possibility of authoring your content. Markdown is a simple markup language that employs plain text characters to determine formatting. This enables you to compose text familiarly while maintaining a rich page layout.

Simplified Creation

Froala Text-to-HTML editor has a simple interface. It has familiar formatting options like you are using MS Word or Google Docs. It is easier for non-coders or those new to HTML to create web content.

Froala Markdown

 

<h2 id=“ftoc-real-time-online-html-editor” class=“ftwp-heading”>Realtime online HTML editor</h2><p>Create and edit ca
href=“https://validator.w3.org/” rel=“nofollow” target=“blank” title=“W3C HTML validator”>W3C valid HTML code</a> without writing a single line of code. The WYSIWYG editor on the left helps non- developers write their own <em>high-quality HTML code.</em></p>

Increased Efficiency

Froala increases efficiency. It automates repetitive tasks, such as code generation and formatting. This lets you focus on creating content and reduces development time.

Froala Markdown2

<h2 id=“ftoc-real-time online-html-editor” class=“ftwp-heading” style=“text-align: center; “>
  Time is Money, <u>And We Are Saving it for You.</u>
</h2>

Visual Representation

The WYSIWYG interface provides a real-time preview of your HTML code. It shows you how your content will appear as you work.

Froala Markdown3

<h1 dir=“ltr” style=“line-height: 2.1;margin-top:12pt;margin-bottom: 12pt;”>
  Visual Representation
</h1>
<p dir=“ltr” style=“line height:2.1;margin-top:12pt;margin-bottom: 12pt;” id=“isPasted”>
  See Your Code is Alway (Right) There.
</p>

Rich Content Capabilities

Froala text-to-HTML editor often offers features beyond basic formatting. It allows you to add images, tables, and other multimedia elements easily and convert them into Pure HTML Code.

Froala Markdown4

 

<h2 id=“ftoc-real-time-online-html-editor” class=“ftwp-heading”>Real- time online HTML editor</h2>
<p>Create and edit <a href=“https://validator.w3.org/” rel=“nofollow” target=“blank” title=“W3C HTML validator”>W3C valid HTML code</a> without writing a single line of code. The WYSIWYG editor on the left helps non- developers write their own <em>high-quality HTML code</em>
</p>
<p align=“center”>
  <img src=“https://froala.com/up- content/uploads/2021/11/agefis-v1108b04XTe-unsplash-scaled.jpg” alt=“Editor photo” class=“fr-fic fr-dii” width=“300”>
</p>
<h3 id=“ftoc- know-some-code” class=“ftup-heading”>Know some code? <span class=“fr- emoticon fr-deletable fr-emoticon-img” style=“background: url(https://cdnjs.cloudflare.com/ajax/libs/emojione/2.0.1/assets/svg/1 f600.svg);”>&nbsp;</span>
</h3>
<p>The editing works both ways, with live visual feedback. Write some markup code on the right, which will appear in the left editor.</p>

Exploring the Power of Froala’s Markdown Plugin

 

While Froala excels at text formatting, it can go even further with the strong Markdown plugin. This add-on enables a more simplified approach to article generation using Markdown, a lightweight formatting language known for its simplicity and efficiency.

Markdown made simple: Write and preview simultaneously

 

Froala’s Markdown plugin adds a user-friendly split-screen view. As you write in Markdown syntax (basic text characters with specified functionalities), the prepared content will appear on the other side in real time. 

 

This visual feedback allows you to create and see your content simultaneously, ensuring it looks exactly as you planned.

Rich Text Formatting is at your fingertips

 

The charm of Froala’s Markdown plugin resides in its extensive support for numerous formatting styles. You can use markdown syntax to create:

 

  • Headings: Organize your information into hierarchies using heading levels (H1, H2, etc.).
  • Emphasis: Highlight important points with bold, italic, or strikethrough formatting.
  • Lists: Present information rationally using ordered or unordered lists.
  • Code Blocks: Display code snippets with suitable formatting to improve readability.
  • Quotes: Use block quotes to highlight quotations or borrowed text.
  • Links and photos: Use Markdown syntax to integrate hyperlinks and photos into your writing seamlessly.
  • Tables: Organize complex data into well-structured and understandable tables.

 

The plugin includes extra features such as footnotes and task lists to meet various content development demands.

Mastering Text Formatting for Compelling Content

Although a fundamental framework is critical for every webpage, genuine interaction resides in engrossing content. Froala enables users to surpass basic skills and effectively format their texts to enhance readability and impact. Its fundamental capabilities can enhance your content as follows:

  • Font Styling: Select from various fonts and modify their dimensions, hue, and weight to establish an aesthetically pleasing design.
  • Aligning Text: To attain the intended layout on a webpage, align the text to the left, right, center, or justify position.
  • Indentation and Line Spacing: Control indentation and line spacing for improved readability, especially for lengthy text sections.
  • Hyperlinks: Effortlessly create hyperlinks by selecting text and specifying the target URL. Froala streamlines the process, removing the need for manual HTML code insertion.
  • Line Breaks and Paragraphs: Insert line breaks and create new paragraphs with a single click, ensuring proper content structure and organization.

Froala Markdown5

Bottom Line

Froala is a powerful text to HTML editor. It lets you easily convert plain text into visually appealing and compelling HTML content. Its essential capabilities create a solid foundation for text formatting, while the Markdown plugin opens up a world of efficient content development. 

Whether you prefer a WYSIWYG approach or the simplicity of Markdown, Froala has you covered, making the shift from plain text to rich online content a seamless and fast procedure. 

 

 

 

Froala & Quasar Integration: Mastering the Best WYSIWYG HTML Editor

Integrating Froala with Quasar

Froala 4.1 release has been a significant step in the history of the developer-friendly best WYSIWYG HTML Editor. It is the release where Froala supports React 18, Angular 15+ with Ivy Engine, and Vue 3. This allows developers to easily integrate Froala into applications using these technologies. For example, Froala can now straightforwardly integrate with Quasar framework V2 which utilizes Vue 3.

In this technical guide, we will explore integrating the powerful Froala as the best WYSIWYG html editor with the Quasar Framework. By leveraging the capabilities of both tools, developers can create rich text editing experiences that meet the needs of modern web development. This guide is designed to be beginner-friendly and will walk you through the process step by step.

What is the Quasar framework?

Quasar framework is an MIT-licensed open-source Vue.js-based framework, which allows you as a web developer to create responsive websites and applications in many flavors quickly:

  • SPAs (Single Page App)
  • SSR (Server-side Rendered App) (+ optional PWA client takeover)
  • PWAs (Progressive Web App)
  • BEX (Browser Extension)
  • Mobile Apps (Android, iOS, …) through Cordova or Capacitor
  • Multi-platform Desktop Apps (using Electron)

Prerequisites

We assume you have a working knowledge of:

  • JavaScript (including some of the newer, ES2015 features)
  • Vue 3
  • How to use the terminal/command line
  • Make sure that you have Node >=14 (or any newer LTS Node.js version) and NPM >=6.14.12 installed on your machine.

Quasar framework integration

Step 1: Setting Up Quasar Project

Open your terminal, navigate to the location where you want to create your project and run the following command:

npm init quasar

you’ll be prompted with some options. Depending on your needs, you can select the CLI type (Vite or Webpack) and you can add things like TypeScript support or a different CSS preprocessor. If you are unsure about any of the options, just take the defaults (hit enter) and you’ll be good to go. You can change the options, except for the CLI type, later if you wish.

Here are our selections:

install Quasar Framework

And we agreed to install project dependencies using NPM.

NPM install

When we were prompted to enter the project name, we entered “my-project“.

Navigate to the project directory

cd my-project

Step 2: Installing Vue WYSIWYG editor

Following the Froala Vue SDK docs, install Froala’s Vue WYSIWYG editor by running the following command:

npm install vue-froala-wysiwyg --save

 Step 3: Integrating Froala Editor

3.1: Import Froala Vue component

As per the Froala document, we need to inject the Froala component before the root Vue app instance is instantiated.

Since you won’t have access to any /main.js file in the Quasar framework (so that Quasar CLI can seamlessly initialize and build the same codebase for SPA/PWA/SSR/Cordova/Electron), Quasar provides an elegant solution to that problem by allowing users to define so-called boot files.

By using Quasar Boot files, you can easily set up and configure the Froala Editor Vue component to be available globally in your Quasar application.

To import the Froala Editor Vue component using Quasar Boot files, you can create a boot file (e.g. froala-editor.js) in the src/boot/ directory of your Quasar project. In this boot file, you can import and configure the Froala Editor Vue component, and then use app.use() to make it available globally.

Here’s an example of how you can set up the best wysiwyg html Editor Vue component in a Quasar Boot file:

//Import Froala Editor plugins
import 'froala-editor/js/plugins.pkgd.min.js';

// Import Froala Editor css files.
import 'froala-editor/css/froala_editor.pkgd.min.css';
import 'froala-editor/css/froala_style.min.css';

// Import Froala Editor component
import VueFroala from 'vue-froala-wysiwyg';

export default async ({ app }) => {
  // Use Froala Editor Vue component
  app.use(VueFroala);
};

After creating the boot file, you need to register it in the quasar.config.js file under the boot property to ensure that it is loaded when your Quasar application starts:

boot: [

'froala-editor'

],

By following this approach, you can easily import the Froala Editor Vue component using Quasar Boot files in your Quasar application.

3.2 Configure and Initializing the Froala Editor

Ideally, you may need to define a route for a subpage where you’ll display the Froala editor but for our basic tutorial, we will edit the main page to display the Froala editor directly.

Open src/pages/IndexPage.vue, and somewhere inside the <template> tag call the Froala component.

<template>
  <q-page class="flex flex-center">
    <froala id="edit" :tag="'textarea'" :config="config" v-model:value="model"></froala>
  </q-page>
</template>

Inside the <script> tag defines the config and model variables where you can pass the editor options and the initialization content.

<script>
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'IndexPage',
  data () {

    return {

      config: {

        heightMin: 300,

        events: {

          initialized: function () {

            console.log('initialized')

          }

        }

      },

      model: '<i>Edit Your Content Here!</i>'

    }

  }
})
</script>

Step 4: Run the project

After the integration is complete, it’s time to run your project to see the editor in action.

To start your local development server and see your application, run the following command in your terminal:

npx quasar dev

This command will start the development server and open the default browser at http://localhost:9000/

Froala runing inside Quasar

You can always stop the server by using the CTRL + C command.

Customizing Your Froala’s Vue WYSIWYG editor

You can learn about the Vue Froala component tags and how to customize the editor from the Vue SDK docs and the following articles:

If you encounter any issues, comment below and I’ll be glad to help.

Conclusion

Integrating Froala Editor with the Quasar Framework can enhance the editing capabilities of your web application. By following the steps outlined in this guide, you can easily incorporate a feature-rich WYSIWYG editor into your project. Experiment with different customization options to tailor the editor to your specific needs and create a seamless editing experience for your users.

Download Froala Editor

Froala Paragraph Styles for Online JavaScript Editors

Paragraph style

Transforming ordinary paragraphs into iconic statements is now within your reach with the powerful Froala online javascript editor. By harnessing the capabilities of the Froala Paragraph Style plugin, you can effortlessly infuse your text with a touch of creativity and sophistication. Whether you aim to emphasize crucial details, craft a distinct visual identity, or simply engage your audience on a deeper level, this plugin equips you with the tools to make your paragraphs truly stand out.

In this article, we will learn how to use the Froala Paragraph Style plugin to enhance the appearance of your text. You can apply different formatting options to make your paragraphs visually striking. Additionally, you can experiment with various font styles, colors, and sizes to create a unique and captivating design. Let’s dive into the features and functionalities of this plugin to elevate your paragraph presentation.

How does the Froala Paragraph Style Plugin Work?

When the Froala Paragraph Style plugin is activated, a button appears on the editor toolbar that opens a list of predefined styles. These styles are defined using CSS classes through the paragraphStyles API option. Choosing a style will apply its corresponding class to the selected paragraphs allowing you to effortlessly enhance the visual appeal of your text. By experimenting with different fonts, colors, and sizes, you can create a unique and captivating design for your paragraphs. This plugin offers a user-friendly way to make your text more engaging and visually appealing, helping you stand out with iconic paragraph styles with your online javascript editor.

paragraph style feature

What does the Froala Paragraph Style Plugin API do?

The Froala Paragraph Style plugin offers two options and one method for customizing paragraph styles in the editor.

The Froala Paragraph Style Plugin Options

1. paragraphStyles:

The paragraphStyles option enables developers to create custom styles for selected paragraphs. It is an object where the property name represents a CSS class and its corresponding value is the text shown in the dropdown menu when the “Paragraph Styles” button is clicked. For example, if the assigned object is

{

'fr-text-gray': 'Gray',

'fr-text-bordered': 'Bordered',

}

This will display two options on the dropdown menu.

  • Gray: once selected, the editor will check the selected paragraph. If it does not have the ‘fr-text-gray’ class, the editor will add it. If the selected paragraph already has that class, the editor will remove it.
  • Bordered: once selected, the editor will check the selected paragraph. If it does not have the ‘fr-text-bordered’ class, the editor will add it. If the selected paragraph already has that class, the editor will remove it.

By default, the paragraphStyles option has the following value:

{

'fr-text-gray': 'Gray',

'fr-text-bordered': 'Bordered',

'fr-text-spaced': 'Spaced',

'fr-text-uppercase': 'Uppercase'

}

You can also define your custom styles and their corresponding classes. When you add your custom class name, make sure you have defined that class in the page stylesheet.

2. paragraphMultipleStyles

Using the paragraphMultipleStyles option, developers can choose whether users can apply a single style or multiple styles from the defined styles in the paragraphStyles option. This gives you control over the number of styles that should be applied to each paragraph using the Paragraph Styles feature. By default, the paragraphMultipleStyles option is set to true.

The Froala Paragraph Style Plugin Methods

The Froala Paragraph Style plugin provides the paragraphStyle.apply(className) method to programmatically apply a specific CSS class to selected paragraphs. This method can be called within editor events or used to create custom buttons for applying paragraph styles.

var editor = new FroalaEditor('.selector', {}, function () {

    // Call the method inside the initialized event.

    editor.paragraphStyle.apply('light');

})

This flexibility in styling empowers you to create visually appealing and unique paragraph designs effortlessly. Experimenting with different font styles, colors, and sizes can help you enhance the visual appeal of your text effectively.

Installation and Setup of The Froala Paragraph Style Plugin

Step 1: Add the Froala Paragraph Style plugin files.

If you have included the Froala packaged files in your web application, then the Paragraph Style plugin JavaScript file is included by default. Skip to step #2.

<link href='{url_based_on_your_download_option}/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />

<script type='text/javascript' src='{url_based_on_your_download_option}/js/froala_editor.pkgd.min.js'></script>

Otherwise, you should include the plugin script file. The plugin doesn’t have a stylesheet file.

<!-- The editor core files -->

<link href='{url_based_on_your_download_option}/css/froala_editor.min.css' rel='stylesheet' type='text/css' />

<script type='text/javascript' src='{url_based_on_your_download_option}/js/froala_editor.min.js'></script>



<!-- The plugin script file -->

<script type='text/javascript' src='{url_based_on_your_download_option}/js/plugins/paragraph_style.min.js'></script>

Step 2: Activate the plugin

By default, the plugin is activated when its JavaScript file is added. However, if the pluginsEnabled option is customized, you should include the paragraphStyle in its assigned value. This ensures that the plugin is active and ready to be used.

new FroalaEditor('#HTMLElement',{

pluginsEnabled: ['image', 'link', 'video', 'paragraphStyle']

});

Step 3: Add the Paragraph Styles Button to the Froala Toolbar

The Paragraph Styles Button is shown by default when the plugin is active. If the toolbarButtons option is customized, include paragraphStyle in the assigned value to display the button.

new FroalaEditor('#HTMLElement',{

    pluginsEnabled: ['image', 'link', 'video', 'paragraphStyle'],

    toolbarButtons: ['bold','insertLink', 'insertImage', 'insertVideo','paragraphStyle']

});

Do the same with the toolbarButtonsMD, toolbarButtonsSM, toolbarButtonsXS options. These options indicate the buttons to be displayed on medium, small, and extra small screens, respectively. By default, these options display the same buttons defined in the toolbarButtons option.

Common use cases of the Paragraph Styles feature

The Paragraph Styles feature is very popular among users as it helps them with

  • Highlighting Important Information: Use different styles to draw attention to key points or important information within your paragraphs.
  • Creating a Consistent Design: Maintain a uniform look throughout your document by applying predefined styles to different sections.
  • Enhancing Readability: Experiment with font styles, colors, and sizes to improve the readability of your text and make it more visually appealing.
  • Adding Emphasis: Apply unique styles to specific paragraphs to emphasize their significance or create a visual hierarchy in your content.

And much more…

Conclusion

The Froala Paragraph Style plugin offers a versatile toolkit to elevate your content presentation. By highlighting important information, creating a consistent design, enhancing readability, and adding emphasis, you can captivate your audience with visually appealing paragraphs. Take your writing to the next level with the power of customization at your fingertips.

Ready to make your paragraphs iconic? Start transforming your text today with the Froala and unleash your creativity like never before!

Download Froala Editor

 

Responsive Video Design for Online JavaScript Editors: A Vue WYSIWYG Guide

Vue WYSIWYG editor

Imagine a world where videos seamlessly adapt to any screen size or device, captivating viewers with their dynamic display. In today’s digital landscape, where content consumption spans across various platforms and gadgets, the need for responsive videos has never been more crucial. Enter the “Responsive Video” feature Froala; an online javascript editor—a game-changer that ensures your videos always shine, regardless of the viewing platform.

We recently answered ten questions about the Froala video plugin customization. However, we did not cover some features, including the “Responsive Video” feature. This article will explore this important feature and demonstrate how to use it with our Vue WYSIWYG editor.

What is the Responsive Video feature in Froala?

The “Responsive Video” feature in Froala online javascript editor allows videos to adjust their size based on the screen or container they are displayed in, ensuring they look good on any device or screen size. Implementing this feature can enhance the user experience by ensuring videos are displayed responsively across various devices.

Unlike the normal mode, you cannot manually resize the added video by dragging and dropping. Additionally, users cannot modify video display or alignment properties. They also cannot change the video dimensions through the Edit video popup.

By enabling this option, the video edit pop-up menu will have three buttons only:

  • Video Replace button
  • Video Remove button
  • Auto-play button

Video feature

Responsive Videos Use Cases

Many use cases can benefit from the Responsive Videos feature. For instance, imagine a scenario where a fashion e-commerce website utilizes the “Responsive Video” feature to showcase dynamic runway videos of its latest collections. These videos seamlessly adapt to the varying screen sizes of users, whether they are browsing on a laptop, tablet, or smartphone. This not only ensures a consistent visual experience for shoppers but also reinforces the brand’s commitment to delivering high-quality content across all devices.

Moreover, consider an educational platform that leverages the responsive video functionality to deliver interactive learning materials to students. With videos adjusting intelligently to fit the screen size, learners can engage with course content effortlessly, regardless of the device they are using. This feature eliminates the need for manual adjustments, allowing educators to focus on creating impactful video lessons without worrying about compatibility issues.

In a marketing context, a travel agency could utilize the “Responsive Video” feature to showcase breathtaking destination videos on their website. By enabling automatic resizing, these videos captivate potential travelers on desktops, tablets, or smartphones, painting an immersive picture of the travel experiences they offer. This seamless display ensures that the agency’s promotional content is visually striking and accessible to a wide audience.

How to enable the “Responsive Video” feature in Froala?

To enable the “Responsive Video” feature in Froala online javascript editor, you can simply set the videoResponsive option to true within the editor configuration.

new FroalaEditor('.selector', {

  videoResponsive: true

});

By activating this feature, videos embedded using Froala will automatically adjust their dimensions to fit the screen or container they are placed in. This dynamic resizing ensures that videos appear correctly sized and formatted on any device or screen resolution.

responsive videos

A Demonstration of the Froala Responsive Video Feature on Vue 3

Let’s create a working example of the Froala Responsive Video Feature on Vue 3. Following a few simple steps, you can easily incorporate this feature into your Froala Vue WYSIWYG editor setup.

Start by creating a new Vue project. Simply use the command below:

vue create video-responsive-project

Once the project is created, navigate to the project directory:

cd video-responsive-project

After that, install the Froala Vue WYSIWYG editor package and its dependencies using npm:

npm install vue-froala-wysiwyg

The vue-froala-wysiwyg NPM package is a wrapper around the Froala editor that simplifies the integration between Froala and Vue.js applications, allowing users to easily create and edit content with a What You See Is What You Get interface.

After installing the vue-froala-wysiwyg package, import it into your project to set up and customize the Froala editor in your Vue.js application.

Open the main Vue component file (main.js)

import { createApp } from 'vue'

import App from './App.vue'

//Import Froala Editor plugins
import 'froala-editor/js/plugins.pkgd.min.js';

// Import Froala Editor css files.
import 'froala-editor/css/froala_editor.pkgd.min.css';
import 'froala-editor/css/froala_style.min.css';


// Import Froala Editor component
import VueFroala from 'vue-froala-wysiwyg';
  • Register the Froala Vue WYSIWYG editor component globally:
const app = createApp(App);          

app.use(VueFroala);

app.mount('#app');

Now you can use the Froala editor component anywhere in your Vue.js project.

The Froala editor component has three attributes:

  1. :tag attribute specifies the tag on which the editor is initialized, typically set to “textarea”.
  2. :config attribute which is used to pass the editor options that allow you to customize the editor settings based on your requirements. It provides flexibility in configuring the editor’s behavior, appearance, and functionality. Using this attribute, you can tailor the Froala editor to suit your specific needs and enhance the editing experience for users interacting with your Vue.js application.
  3. v-model:value attribute is used to display and edit content in the editor with two-way binding.

To enable the video responsive feature, we will set the videoResponsive option to true inside the :config attribute.

Open the “App.vue” file and edit it as

<template>
    <froala
    :tag="'textarea'"
    :config="config" 
  ></froala>

</template>
<script>
export default {
  name: "App",
    data () {

    return {

      config: {
        videoResponsive: true,
        toolbarButtons: ['insertVideo']
        }
      }
    },
  }
</script>

Run the below NPM command to run your Vue application on your local development server.

npm run serve

Visit http://localhost:8080 to view the running example we created. Note, on the Froala editor’s toolbar, there is a button to insert Videos. When a video is inserted, it automatically spans the full width of the editor and cannot be manually resized.

Conclusion

By incorporating the “Responsive Video” feature in Froala, you can ensure that videos adjust their size according to the screen or container they are displayed in, providing a consistent viewing experience across various devices. This dynamic resizing feature enhances user interaction by optimizing video displays on different screen sizes.

Froala can act as your Vue WYSIWYG editor. Enabling the videoResponsive option in the Froala Vue WYSIWYG editor allows for seamless integration of this feature, making it easy to create and edit responsive videos within your Vue.js application.

Building a Support System with Laravel PHP and Froala HTML Editor Sofware – part 3

Froala WYSIWYG Editor PHP SDK

In this article, we will continue building a rich-text support system using the Laravel PHP Framework and the Froala html editor software. If you haven’t read the previous articles in this series, we recommend doing so as we will be building upon them.

 

 

Part 1: Building a Support System Using Laravel PHP Framework and Froala Rich Text Editor

Part 2: Simplify Froala Image Management in Laravel using Froala PHP SDK

A Quick Recap

In the previous articles, we built a page containing a form for users to send their issues to the support team. We used Froala to allow users to send a rich-text message. Users can include images within their messages to help them describe their issues better. We used Froala PHP SDK to validate the images and store them on the server. Once the user is done with their messages and submits the form, the data is saved into the database using our html editor software.

Retrieving and Displaying User Messages for Site Administrators

In this article, we will learn how to retrieve user messages from the database and display them to the site administrators. This will allow the administrators to respond to the users’ issues. We will not cover the implementation of a login system for the administrators, as there are already many resources available for setting up authentication in Laravel. Instead, we will focus on creating a page that lists all the user tickets and another page that displays the details of a specific ticket for the administrators to respond to.

List User Requests

Let’s create a new resource controller to allow the support team to review and read the submitted requests.

php artisan make:controller AdminRequestController --resource

Add the route in web.php

Route::resources(['admin/requests' => App\Http\Controllers\AdminRequestController::class]);

Open the AdminRequestController.php and add the following line at the top to allow us to use the Request model within the controller.

use App\Models\Request as RequestModel;

Edit the index function to

    public function index()
    {
        //
        $requests = RequestModel::all();

        return view('requests.index', ['request'=>$request]);

    }

The above code fetches all the user messages from the database using the RequestModel::all() method. Then it passes the retrieved data to the requests.index view.

We need to create the requests.index view to display the user tickets on the page. Let’s create a new file called index.blade.php in the resources/views/requests directory. In this file, we can iterate over the $requests variable using a @foreach loop and display the necessary information for each ticket.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Support App.</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">

        <!-- Styles -->
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>


    </head>
    <body>
        <div class="container">
            <div class="row justify-content-center">
                <h1 class="col-md-8 my-5 text-center">
                    All Requests
                </h1>

            </div>
            <div class="row justify-content-center">
                <table class="table">
                    <thead>
                      <tr>
                        <th scope="col">#</th>
                        <th scope="col">Subject</th>
                        <th scope="col">date</th>
                        <th scope="col">View</th>
                      </tr>
                    </thead>
                    <tbody>
                        @foreach ($requests as $i => $request)


                      <tr>
                        <th scope="row">{{$i}}</th>
                        <td>{{$request->subject}}</td>
                        <td>{{$request->created_at}}</td>
                        <td>
                            <a href="{{route('requests.show', $request->id )}}" type="button" class="btn btn-info">View</a>
                        </td>
                      </tr>
                      @endforeach

                    </tbody>
                  </table>
            </div>
        </div>
    </body>

Once we have the index.blade.php view set up, we can navigate to the /admin/requests route to see the list of user tickets.

Laravel support system

Request Details View

Next to each ticket, there is a button to view the ticket details. Clicking on it redirects the support team member to the /admin/requests/{ID} URL, where ID is the unique identifier of the ticket.

To handle the route for viewing a specific ticket, we need to update the AdminRequestController show function. This function will retrieve the ticket details from the database based on the ID and pass them to the requests.show view.

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

        $request = RequestModel::findOrFail($id);

        return view('requests.show', ['request'=>$request]);
    }

Next, let’s create a new file called show.blade.php in the resources/views/requests directory. In this file, we can display the details of a specific ticket by accessing the properties of the $request variable. We can show the subject, description, date, and any other relevant information.

On this page, it is crucial to include the CSS stylesheet provided below in the page header to ensure the accurate display of the data that users entered using the Froala html editor software.

<link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_style.min.css' rel='stylesheet' type='text/css' />

The show.blade.php full code is:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Support App.</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">

        <!-- Styles -->
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>

        <!-- CSS file for showing Froala content outside the editor -->
        <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />


    </head>
    <body>
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-md-8 my-5 ">
                <h1>
                    {{$request->subject}}
                </h1>
                <p>{!!$request->request!!}</p>
                </div>
                <div class="card col-md-4 my-5 ">
                    <div class="card-header">
                        Requester Details
                    </div>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item">{{$request->name}}</li>
                        <li class="list-group-item">{{$request->email}}</li>
                        <li class="list-group-item">{{$request->created_at}}</li>
                    </ul>
                </div>


            </div>

        </div>
    </body>

The above code will display the subject of the ticket, the content of the request (which includes HTML code), and the details of the requester’s name and email. We use Bootstrap to style the card that contains the requester details.

Displaying Froala Editor content Outside The Editor

In addition to adding froala_style.min.css to the header, it is important to note that we use {!! !!} instead of {{ }} to display the request variable that contains Froala Content. This is because it contains HTML code, which should be rendered as is without any character escaping.

Laravel PHP support system ticket details

The support team can now view the ticket and requester details. They have the option to manually email the requester with a solution to their issue. We could improve this process by including a “Reply” button that opens a Froala editor. This editor would enable the support team to draft a message that is automatically sent back to the requester. If you would like me to address this topic in another article, please leave a comment.

Conclusion

In this article, we have learned how to configure the index view to showcase a list of user tickets. We have also explored handling the route for viewing a specific ticket and presenting its details in the show.blade.php file. Bootstrap was utilized for styling, along with including the necessary CSS files for displaying Froala content outside the editor. This ensures that user-entered content is displayed accurately.

As a next step, consider enhancing system security by implementing authentication features that limit access to authorized administrators. Laravel provides built-in authentication capabilities that can be seamlessly integrated into the support system, offering an additional layer of control and privacy.

Overall, this article emphasizes the simplicity and effectiveness of showcasing Froala content outside the editor within the Laravel PHP framework. With this knowledge, you can handle user tickets and provide exceptional support within your application.

Start using Froala in your Laravel application now. For any queries or assistance, do not hesitate to reach out to us. Happy coding!

Froala Image Management in Laravel: Easy for HTML Code Writers

Froala PHP SDK

If you’re using the Froala html code writer in your Laravel project to offer rich-text editing options for your users, they can use it to insert images in their content. These images are not saved to your PHP server by default, but you need to handle storing these images using the Froala events. Since uploading images to a PHP server could be a complex task for many developers, Froala offers a PHP SDK to simplify this process. The SDK provides a set of functions and methods that streamline the image management process, allowing you to upload, edit, and delete images with ease.

This article is the second part of the “Building a Support System Using Laravel PHP Framework and Froala html editor software“ series. We will use the Froala PHP SDK to enhance the support system we created by adding the functionality to store, validate, and remove images in the contact form. By doing this, we can display the uploaded images within the “Request Details” field to the admin at a later stage.

Get Started

To get started, you’ll need to install the Froala PHP SDK in your Laravel project. Include the SDK as a dependency in your composer.json file.

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "php": "^7.3|^8.0",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.75",
        "laravel/sanctum": "^2.11",
        "laravel/tinker": "^2.5",
        "twbs/bootstrap": "5.3.2",
        "froala/wysiwyg-editor-php-sdk" : ""
    },
    "require-dev": {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^5.10",
        "phpunit/phpunit": "^9.5.10"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

Run the composer update command

composer update

This command will update the dependencies specified in the composer.json file and install the latest versions of the packages.

Before we dive in, make sure your server has the FileInFo extension enabled. You can do this by opening your server “php.ini“ file and removing the “;“ before “extension=fileinfo” if it exists.

The SDK also requires the Imagick extension to be enabled. To install the Imagick extension on XAMPP, you can follow these steps:

  1. Download the appropriate Imagick DLL file for your PHP version from the PECL website.
  1. Copy the downloaded php_imagick.dll file to the “ext” directory in your XAMPP installation.
  1. Copy other DLL files to the PHP root directory (where you have php.exe). Ex: For XAMPP users, `C:\xampp\php\` folder.
  2. Open the “php.ini” file in the “php” directory of your XAMPP installation.
  3. Add the following line to the “php.ini” file:

extension=php_imagick.dll

  1. Save the changes to the “php.ini” file and restart the Apache server in XAMPP.

Once you have completed these steps, the Imagick extension will be installed and ready to be used in your XAMPP environment. Now you can proceed to use the Froala html code writer PHP SDK in your Laravel application.

Upload images using the Froala PHP SDK

Before proceeding with the process of uploading images, it is necessary to configure certain Froala API options and events:

  • imageUploadParam is the name of the parameter that contains the image file information in the upload request. The default value is “file,” but you can change it to whatever name you want.
  • imageUploadURL is the URL where the upload request is being made.
  • imageUploadParams are additional parameters that are passed in the upload request to the server.
  • imageUploadMethod is the HTTP request type.
  • imageMaxSize is the maximum image size that can be uploaded.
  • imageAllowedTypes is an array with the image types allowed to be uploaded.
  • image.beforeUpload event is triggered before starting the upload request and it can be used to change the upload params or cancel the action.
  • image.uploaded event is triggered after a successful image upload request, but before inserting the image into the editor.
  • image.inserted event is triggered after inserting the image into the editor.
  • image.replaced event is triggered after replacing the image in the editor.
  • image.error event is triggered if any errors occur during the upload process.

Go ahead to the `welcome.blade.php` and edit the script to

       <script>
            // to protect your application from cross-site request forgery (CSRF) 
            let token = document.querySelector('[name="_token"]').value;

            new FroalaEditor("#request", {

                toolbarButtons: [
                    ['fontSize', 'bold', 'italic', 'underline', 'strikeThrough'],
                    [ 'alignLeft', 'alignCenter', 'alignRight', 'alignJustify','textColor', 'backgroundColor'],
                    ['formatOLSimple', 'formatUL', 'insertLink','insertImage','insertFile'],
                ],

                //Set the request type
                imageUploadMethod:'POST',
                
                //Set the image upload URl.
                imageUploadURL:'/support-app/public/upload',

                //To avoid getting 419 bad request
                imageUploadParams: {
                    _token: token
                }
            });
        </script>

The code above configures the image upload method and URL so that when a user inserts an image in the editor, an HTTP request is automatically sent to the ‘/upload’ URL.

To prevent server errors and protect against CSRF attacks, we included the CSRF token generated by Laravel for each active user session in the request. This was done using the imageUploadParams option in Froala.

Next, we need to create a route and controller to handle the HTTP request for inserted images. Use the following command to generate the controller.

php artisan make:controller ImageHandlerController

create Laravel controller

Then, open our “web.php” and define a route for the URL assigned to the imageUploadURL option.

use App\Http\Controllers\ImageHandlerController;




Route::post('/upload', [ImageHandlerController::class, 'store']);

Open the newly created controller to add the store function. In this function, we will use the Froala PHP SDK upload method to store the uploaded images in the storage\app\public\uploads folder.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use FroalaEditor_Image;

class ImageHandlerController extends Controller
{
    /**
     * Store the uploaded image
     */
    public function store()
    {
        return FroalaEditor_Image::upload('/support-app/storage/app/public/uploads/');
    }
}

The upload method returns the URL of the uploaded image, which is then assigned to the src attribute of the inserted image by Froala.

Now, when a user inserts an image in the Froala html code writer, it will be automatically uploaded to the specified URL and stored in the designated folder.

After submitting the form, the database will store the permanent URLs of the inserted images within the “request details” content. These images can then be displayed on the admin dashboard for reviewing user requests.

Server-side image upload validation

Froala editor offers imageAllowedTypes and imageMaxSize options for client-side validation of image type and size. Additionally, the Froala PHP SDK upload method enables server-side validation of uploaded images. This provides an extra layer of security and ensures that only valid images are accepted.

The second parameter of the FroalaEditor_Image::upload accepts an array for validating the uploaded image.

To validate image uploads on the server side, make the following modifications to the store function in the ImageHandlerController

    public function store()
    {
        $options = array(
            'validation' => array(
            'allowedExts' => array('jpeg', 'jpg'),
            'allowedMimeTypes' => array('image/jpeg', 'image/pjpeg')
            )
        );
        return FroalaEditor_Image::upload('/support-app/storage/app/public/uploads/', $options);
    }

The code above sets Froala to accept only JPEG and JPG images. Uploading any other image type will trigger an error message.

Froala PHP SDK - server-side validation

By implementing image upload validation on the server side, we can ensure that only valid images are accepted and stored in the designated folder. This helps to maintain the integrity and security of the application.

Removing Images From the Server

Unlike uploading, Froala does not have a built-in option for making a server request to delete uploaded images. However, we can utilize the froalaEditor.image.removed event to send an AJAX request to the server when the user selects the “remove image” button. This event is triggered after the image has been removed from the editable area.

Open welcome.blade.php and add the following code to the Froala initialization code.

                events:{
                    'image.beforeRemove': function ($img){
                       
                        const url = '/support-app/public/image-delete',
                        params ={
                            src: $img[0].src
                        };

                        // Send Ajax call to delete the image
                        fetch(url,{
                            method: 'delete',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': token
                            },
                            body: JSON.stringify(params)
                        })
                        .then(response => {
                            const reposList = response.json();
                            console.log(reposList);
                        })
                        .catch(err => console.log(err))
                    }
                }

The code above sends a delete request to the “/image-delete” URL, including the image src attribute of the image that will be deleted.

Let’s define the “/image-delete” URL in the “web.php“ file.

Route::delete('/image-delete/', [ImageHandlerController::class, 'remove']);

This route action is controlled by the remove method in the ImageHandlerController. Open the `ImageHandlerController.php` to define this method.

    /**
     * Remove the uploaded image
     */
    public function remove(Request $request)
    {
        $search = request()->getScheme().'://'.$_SERVER['SERVER_NAME']; //
        $src= str_replace($search, '', $request->src);
        return FroalaEditor_Image::delete($src);
    }

The remove method utilizes the FroalaEditor_Image::delete method from the Froala PHP SDK to delete the image from the server.

Testing Image Upload and Removal Functionality

To test if everything is working properly, follow these steps:

  1. Upload an image to the editor.
  2. Navigate to the storage\app\public\uploads directory to view the uploaded image. The image should be there.
  3. Return to the editor and click on the image. Then, choose the “Remove Image” option from the “Edit Image” popup.
  4. Open the storage\app\public\uploads directory again. The image shouldn’t be there anymore.

froala php sdk and Laravel

Replace the uploaded image

The Froala “Edit Image“ popup allows users by default to replace the current image with a new one. This enhances the user experience by enabling them to quickly update the image without needing to remove the current uploaded image first. However, while Froala automatically replaces the image on the front-end, the functionality of removing the selected image from the server and storing the new one must be implemented separately. We can utilize the Froala PHP SDK to accomplish this task efficiently. Nonetheless, this article will not cover the implementation process. Instead, we will hide the “Replace Image” option, requiring users to remove the existing image before uploading a new one.

Edit the Froala initialization code at welcome.blade.php to

            // to protect your application from cross-site request forgery (CSRF)
            let token = document.querySelector('[name="_token"]').value;

            new FroalaEditor("#request", {

                toolbarButtons: [
                    ['fontSize', 'bold', 'italic', 'underline', 'strikeThrough'],
                    [ 'alignLeft', 'alignCenter', 'alignRight', 'alignJustify','textColor', 'backgroundColor'],
                    ['formatOLSimple', 'formatUL', 'insertLink','insertImage','insertFile'],
                ],

                imageEditButtons: ['imageAlign', 'imageCaption', 'imageRemove', '|', 'imageLink', 'linkOpen', 'linkEdit', 'linkRemove', '-', 'imageDisplay', 'imageStyle', 'imageAlt', 'imageSize'],


                //imageMaxSize: 1024 * 1024 * 3,

                //Set the request type
                imageUploadMethod:'POST',

                //Set the image upload URl.
                imageUploadURL:'/support-app/public/upload',

                //To avoid getting 419 bad request
                imageUploadParams: {
                    _token: token
                },

                events:{
                    'image.beforeRemove': function ($img){

                        const url = '/support-app/public/image-delete',
                        params ={
                            src: $img[0].src
                        };

                        // Send Ajax call to delete the image
                        fetch(url,{
                            method: 'delete',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': token
                            },
                            body: JSON.stringify(params)
                        })
                        .then(response => {
                            const reposList = response.json();
                            console.log(reposList);
                        })
                        .catch(err => console.log(err))
                    }
                }


            });

In the above code, we customized the `imageEditButtons` API option by removing the ‘imageReplace’ from the array.

Conclusion

Integrating the Froala PHP SDK into your Laravel project provides a seamless solution for handling image management within the Froala JavaScript WYSIWYG editor. By leveraging the SDK’s functions and methods, developers can simplify the process of uploading, validating, and deleting images, offering a user-friendly experience for content creators.

Incorporating the Froala PHP SDK into your Laravel project not only simplifies image management but also enhances the support system you’ve built. By enabling users to upload and display images within the contact form, you can provide a more interactive and engaging experience for both users and administrators.

As you continue to build your Laravel project and leverage the power of the Froala PHP SDK, we hope that the insights and instructions provided in this article have proven helpful. Remember to stay updated with the latest SDK version and explore additional features and functionalities it offers. With Froala and Laravel at your disposal, you can create a truly dynamic and visually appealing content creation platform.

Optimizing Vue Applications for HTML Code Writers: Initializing Froala Editor on Click

Froala Vue WYSIWYG editor Optimization

The Froala Vue WYSIWYG Editor is a powerful tool that allows developers to easily incorporate a rich text editing experience into their Vue.js applications. With its user-friendly interface and extensive customization options, the Froala html code writer provides a seamless editing experience for users.

We have covered the integration process of Froala and Vue before. However, in some applications, developers may need to initialize the Froala Vue WYSIWYG Editor by clicking on a certain element. By manually initializing the editor on click, developers can control when the editor appears on the page. This helps optimize your application load speed especially if you have more than one editor on the page.

In this article, we will guide you through the process of initializing the Froala Vue WYSIWYG Editor on click. We will cover the necessary prerequisites, step-by-step instructions, and customization options to help you make the most out of this powerful editing tool.

By the end of this guide, you will have a solid understanding of how to set up and initialize the editor on click. So let’s dive in and explore the benefits and importance of on-click initialization for the Froala Vue WYSIWYG Editor.

Optimizing Vue Applications

prerequisites

We assume you have a working knowledge of:

  • JavaScript (including some of the newer, ES2015 features)
  • Vue 3
  • How to use the terminal/command line
  • Node and npm

Create a simple Vue project.

To create a new Vue.js project, run the following commands.

npm install -g @vue/cli

vue create my-froala-vue-app

The above commands will install the Vue CLI globally on your machine and then create a new Vue project called “my-froala-vue-app”.

Install the Froala WYSIWYG Editor package.

Next, you need to install the Froala WYSIWYG Editor package. To do this, navigate to your project directory and run the following command:

cd my-froala-vue-app

npm install vue-froala-wysiwyg

This will install the Froala WYSIWYG Editor package and its dependencies into your project.

Import the Froala WYSIWYG Editor Component

To use the Froala WYSIWYG Editor in your Vue application, you need to import the component. Copy the following code into your “main.js” file.

import { createApp } from "vue";
import App from "./App.vue";

//Import Froala Editor plugins
import "froala-editor/js/plugins.pkgd.min.js";

// Import Froala Editor css files.
import "froala-editor/css/froala_editor.pkgd.min.css";
import "froala-editor/css/froala_style.min.css";

// Import Froala Editor component
import VueFroala from "vue-froala-wysiwyg";

const app = createApp(App);

app.use(VueFroala);
app.mount("#app");

This code imports the VueFroala component from the `vue-froala-wysiwyg` package and registers it. This allows you to use the Froala WYSIWYG Editor component in your Vue components.

Initialize the Froala Vue WYSIWYG Editor on Click

We will add the following code to the “app.vue” file.

<template>
  <div id="app">
    <h1>Vue adapter for the Froala WYSIWYG editor</h1>

    <div class="sample">
      <h2>Sample 4: Manual Initialization</h2>
      <button class="manual" v-on:click="createEditor()" v-if="!showEditor">
        Initialize Editor
      </button>
      <button v-on:click="destroyEditor()" v-if="showEditor">
        Close Editor
      </button>
      <button v-on:click="deleteAll()" v-if="showEditor">Delete All</button>
      <froala
        id="sample5"
        :onManualControllerReady="initialize"
        v-model:value="sample3Text"
      >
        <template v-slot>
          <div>
            Check out the
            <a href="https://www.froala.com/wysiwyg-editor">Froala Editor</a>
          </div>
        </template>
      </froala>
    </div>
  </div>
</template>

<script>
export default {
  name: "app",
  data() {
    return {
      // Sample 4
      sample3Text: null,
      initControls: null,
      showEditor: false,
      deleteAll: null,
      destroyEditor: () => {
        this.initControls.destroy();
        this.showEditor = false;
      },
      createEditor: () => {
        this.initControls.initialize();
        this.showEditor = true;
      },
      initialize: (initControls) => {
        this.initControls = initControls;
        this.deleteAll = () => {
          this.initControls.getEditor().html.set("");
          this.initControls.getEditor().undo.reset();
          this.initControls.getEditor().undo.saveStep();
        };
      },
    };
  },
  created() {},
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin-top: 60px;
}
body {
  padding: 20px;
}

.sample {
  padding-bottom: 50px;
  margin-left: 30px;
  border-top: 1px solid lightgray;
}

.manual {
  margin-bottom: 20px;
}

.button {
  margin-left: 5px;
}
</style>

Let’s break down the code step by step:

The code above defines three buttons: one for initializing the editor when it is not loaded on the page, and the other two buttons appear when the editor is shown. One button is for destroying the editor, and the other is used to clear the editor’s contents.

<h2>Sample 4: Manual Initialization</h2>
<button class="manual" v-on:click="createEditor()" v-if="!showEditor">
  Initialize Editor
</button>
<button v-on:click="destroyEditor()" v-if="showEditor">
 Close Editor
</button>
<button v-on:click="deleteAll()" v-if="showEditor">Delete All</button>

The showEditor is a data property that determines whether the editor is currently shown or not. It is initially set to false. The createEditor method is called when the “Initialize Editor” button is clicked, and it sets showEditor to true and initializes the editor. The destroyEditor method is called when the “Close Editor” button is clicked, and it destroys the editor and sets showEditor back to false. The deleteAll method is called when the “Delete All” button is clicked, and it clears the editor contents.

Our “app.vue” code also includes the Froala Vue component. It has an id of sample5 and a v-model binding to the sample3Text data property. This :onManualControllerReady is used to bind the initialize method to the Froala editor’s manual controller. This allows us to access the editor’s methods and perform actions such as clearing the editor’s contents.

      <froala
        id="sample5"
        :onManualControllerReady="initialize"
        v-model:value="sample3Text"
      >

The initialize method is called when the editor is initialized, and it receives the initControls object as a parameter. Developers can obtain instances of the FroalaEditor object by using the getEditor() method of the initControls object. This allows them to easily access and utilize any Froala API method.

<script>
export default {
  name: "app",
  data() {
    return {
      // Sample 4
      sample3Text: null,
      initControls: null,
      showEditor: false,
      deleteAll: null,
      destroyEditor: () => {
        this.initControls.destroy();
        this.showEditor = false;
      },
      createEditor: () => {
        this.initControls.initialize();
        this.showEditor = true;
      },
      initialize: (initControls) => {
        this.initControls = initControls;
        this.deleteAll = () => {
          this.initControls.getEditor().html.set("");
          this.initControls.getEditor().undo.reset();
          this.initControls.getEditor().undo.saveStep();
        };
      },
    };
  },
  created() {},
};
</script>

Finally, we have a `template` block inside the Froala component where we can add additional HTML content. In this example, we have simple text and a link to the Froala Editor website.

  <template v-slot>
    <div>
      Check out the
      <a href="https://www.froala.com/wysiwyg-editor">Froala Editor</a>
    </div>
  </template>

That’s it! You have now created a simple Vue project with the Froala html code writer integrated. You can now run your Vue project and see the Froala Editor in action.

Run the Vue App

To run the Vue app and see the Froala Vue WYSIWYG Editor in action, navigate to your project directory and run the following command:

npm run serve

This will start the development server at http://localhost:8080

The benefits of loading Froala on click

Loading the Froala Vue WYSIWYG editor on click offers several benefits for developers. It helps improve the initial loading time of the webpage. By deferring the loading of the editor until it is actually needed, developers can ensure that their web pages load quickly and efficiently. This can lead to a better user experience, as visitors won’t have to wait for the editor to load if they don’t plan on using it.

Additionally, loading the Froala editor on click allows developers to save resources and optimize performance. Since the editor is only loaded when necessary, it doesn’t consume unnecessary memory or processing power. This can help improve the overall performance of the webpage and prevent any unnecessary strain on the user’s device.

Moreover, loading the Froala editor on click provides a more seamless and intuitive user experience. Instead of having the editor visible at all times, it only appears when the user explicitly chooses to use it. This allows for a cleaner and less cluttered interface, making it easier for users to focus on the task at hand.

Conclusion

The Froala WYSIWYG Editor is a powerful tool for creating rich text content in web applications. In this tutorial, we learned how to integrate the Froala Editor with a Vue.js project and initialize it on click. This approach offers numerous benefits in terms of performance, user experience, and resource optimization.

Now that you have learned how to integrate and initialize the Froala Editor on click, why not give it a try in your own Vue.js projects? With its user-friendly interface and extensive customization options, the Froala Editor offers a seamless editing experience for your users. Experience the power of the Froala Editor today and enhance the content creation capabilities of your web applications.

Get started with the Froala Vue WYSIWYG Editor now and unleash the full potential of your web applications!

Build a Google Docs-like Online JavaScript Editor Using Froala Vue WYSIWYG Editor

Vue WYSIWYG editor

Google Docs has become a household name when it comes to online word processing. If you would like to build a similar application, there is a wide range of development languages and frameworks to use. One of the top options is Vue.js. With our Froala online javascript editor, you can have a similar one for your inhouse app.

Vue.js, a progressive JavaScript framework, has gained significant traction in the web development community due to its simplicity, flexibility, and excellent performance. Leveraging Vue.js allows developers to create powerful and interactive user interfaces, making it an ideal choice for building a Google Docs alternative.

While building a document editing application from scratch is a viable option, it can be a time-consuming and complex process. This is where third-party WYSIWYG (What You See Is What You Get) editors come into play. These editors provide a pre-built foundation for creating rich text editors, saving developers valuable time and effort. One such editor is the Froala Vue WYSIWYG editor, which offers a comprehensive set of features, customization options, and compatibility with Vue.js.

In this article, we will learn how to use the Froala Vue WYSIWYG editor to build a Google Docs alternative. We will explore its features, and demonstrate its suitability for implementing web document editing.

Vue web document editing

Understanding the Froala Vue WYSIWYG Editor

The Froala Vue WYSIWYG Editor stands out as a top choice when it comes to building a Google Docs alternative. Its extensive range of features and rapid development capabilities make it an ideal solution for creating rich text editors. Here are some of its features:

  • Rich Text Editing: The Froala Vue WYSIWYG editor provides a comprehensive set of tools and options for editing text. Users can easily format text, change fonts, styles, and colors, add links, insert images and videos, create tables, and more.
  • Vue.js Integration: Froala 4.1 provides a Vue component that can be easily integrated into Vue.js projects, making it simple to incorporate rich text editing capabilities into Vue.js applications.
  • Document-ready mode: The Froala Vue WYSIWYG editor has a document-ready mode that makes the editor interface resemble a word processor document by default.
  • Cross-browser and Cross-platform Compatibility: The editor is designed to work seamlessly across different browsers and platforms, ensuring a consistent editing experience for users regardless of their device or browser choice.
  • Responsive Design: The editor is built with a responsive design, which means it automatically adapts to different screen sizes and resolutions, providing an optimal editing experience on both desktop and mobile devices.
  • Accessibility: The editor is designed with accessibility in mind, ensuring that users with disabilities can easily navigate and use the editing interface. It includes features like keyboard navigation, support for screen readers, and adherence to accessibility standards.
  • Extensibility: The editor is highly extensible, allowing developers to customize and extend its functionality to meet specific requirements. It provides a plugin system that enables the addition of custom buttons, options, and features.
  • Modern and User-Friendly Interface: The editor features a modern and intuitive user interface, with a clean and clutter-free design. It offers a seamless editing experience, allowing users to focus on content creation without distractions.
  • Comprehensive Documentation and Support: Froala provides extensive documentation and support resources for developers using their editor. This includes detailed API documentation, guides on how to get started, examples, and more.

By leveraging the Froala Vue WYSIWYG editor, developers can quickly and easily build a Google Docs alternative that meets their specific needs. Whether it’s for collaborative document editing, online word processing, or any other application that requires rich text editing capabilities, the Froala Vue WYSIWYG editor provides a reliable and feature-rich solution.

In the next section, we will dive into the process of integrating the Froala Vue WYSIWYG editor into a Vue.js project.

Setting up the Development Environment

You’ll need to install the Froala Vue component to use the Froala Vue WYSIWYG editor in your Vue.js project. Here’s a step-by-step guide:

  1. Start by creating a new Vue.js project using the Vue CLI. Open your terminal and run the following command:
vue create my-project
  1. Next, navigate to the project directory:
cd my-project
  1. Install the Froala Vue WYSIWYG editor package and its dependencies using npm:
npm install vue-froala-wysiwyg

This command will install the required packages and add them to your project’s package.json file.

Configuration and Integration of Froala Vue WYSIWYG Editor with a Vue.js Project

Once the necessary dependencies are installed, you can configure and integrate the Froala Vue WYSIWYG editor with your Vue.js project.

  1. Open the main Vue component file (main.js) and import the Froala Vue WYSIWYG editor component:
import { createApp } from 'vue'
import App from './App.vue'

//Import Froala Editor plugins
import 'froala-editor/js/plugins.pkgd.min.js';


// Import Froala Editor css files.
import 'froala-editor/css/froala_editor.pkgd.min.css';
import 'froala-editor/css/froala_style.min.css';


// Import Froala Editor component
import VueFroala from 'vue-froala-wysiwyg';
  1. Register the Froala Vue WYSIWYG editor component globally:
const app = createApp(App);          

app.use(VueFroala);
app.mount('#app');

This step allows you to use the Froala online javascript editor component anywhere in your Vue.js project.

  1. Finally, you can start using the Froala Vue WYSIWYG editor component in your Vue.js templates. For example, in the (App.vue) file:
<template>
    <froala
    id="edit"
    :tag="'textarea'"
  ></froala>

</template>
<script>
export default {
  name: "App",
  }}
</script>

By doing this, you have successfully set up the development environment and integrated the Froala Vue WYSIWYG editor into your Vue.js project.

  1. Run the below NPM command to run your Vue application on your local development server.
npm run serve

Now you can start using the editor’s features to create and edit HTML content at http://localhost:8080

Optimizing the Froala Vue WYSIWYG Editor for a Google Docs-Like Layout

To make your Froala Vue online javascript editor layout look like Google Docs and other online document editing applications, you need to enable the documentReady API option. Enabling this option will automatically set the optimal settings for creating online documents. The editor toolbar button will be customized to display the most frequently used buttons for these types of applications. The print and export as PDF buttons will be moved to a more visible location. The editable area will be expanded, and a margin will be added between it and the editor’s borders.

Open the App.vue file and edit your template to

<template>
    <froala
    id="edit"
    :tag="'textarea'"
    :config="config"
  ></froala>

</template>
<script>
export default {
  name: "App",
  data() {
    return {
      config: {
        documentReady: true
      }
    };
  },
  
  };
</script>

Conclusion

The Froala Vue WYSIWYG editor is a powerful tool for building a Google Docs alternative or any other application that requires rich text editing capabilities. It offers a seamless editing experience with its responsive design, accessibility features, and modern user-friendly interface.

To integrate the Froala Vue WYSIWYG editor into a Vue.js project, you need to set up the development environment by installing the necessary dependencies. Then, you can configure and integrate the editor by importing the component, registering it globally, and using it in your Vue.js templates.

To optimize the editor for a Google Docs-like layout, you can enable the `documentReady` API option, which sets optimal settings for creating online documents.

Learn more about Froala Vue WYSIWYG editor.

Using Froala as a Vue Visual HTML Editor for Markdown: A Guide

Froala WYSIWYG editor

If you want to provide text formatting options for your users, you have two popular choices: a visual html editor or a Markdown editor. Froala offers both options. Essentially, Froala is a visual html editor with the ability to convert to a Markdown editor. Since the Froala V4.1 release, it has supported Vue 3. This makes it a powerful Vue 3 WYSIWYG Markdown editor component. In this article, we will learn how to use Froala as a Markdown editor in your Vue app.

What’s a Markdown editor?

A Markdown editor is a text editor that allows users to write using Markdown syntax. Markdown is a lightweight markup language that uses plain text formatting to create structured documents. It is easy to read and write, making it a popular choice for content creation. Markdown editors provide a user-friendly interface for writing and editing Markdown content. With a Markdown editor, users can create well-formatted documents without needing to learn complex HTML or CSS. It is a great tool for users who want a simple and efficient way to create and format content.

What is the difference between WYSIWYG and Markdown editors?

A WYSIWYG editor, which stands for “What You See Is What You Get”, allows users to create and edit content in a visual manner. Users can see the final appearance of the content as they are editing it, including formatting, images, and other elements. It provides a more intuitive and familiar experience for users who are not familiar with coding or markup languages.

On the other hand, a Markdown editor requires users to write content using Markdown syntax. Markdown is a plain text formatting language that uses simple syntax to indicate formatting elements such as headings, lists, links, and more.

Is Froala a WYSIWYG editor or a Markdown editor?

Froala is primarily a WYSIWYG editor, but it also has a Markdown plugin that you can use to enable editing content using Markdown syntax. This allows users to have the flexibility to choose between the two editing modes based on their preferences and needs.

Does Froala Support Vue 3?

Froala V4.1 supports Vue 3 out of the box. This means you can easily integrate Froala visual html editor into your Vue 3 app and take advantage of its powerful features. With the Froala Vue component, you can create a WYSIWYG editor or a Markdown editor in your Vue app with just a few lines of code.

How do we integrate the Froala WYSIWYG editor with Vue 3?

Check out this guide on integrating the Froala WYSIWYG editor with Vue 3 for a detailed explanation. In summary, you will need to install the Froala Vue package using npm.

npm install -g @vue/cli

vue create my-froala-vue-app

cd my-froala-vue-app

npm install vue-froala-wysiwyg --save

Once installed, you can import the Froala Vue component in the “main.js” file.

import { createApp } from 'vue'
import App from './App.vue'

//Import Froala Editor plugins
import 'froala-editor/js/plugins.pkgd.min.js';


// Import Froala Editor css files.
import 'froala-editor/css/froala_editor.pkgd.min.css';
import 'froala-editor/css/froala_style.min.css';


// Import Froala Editor component
import VueFroala from 'vue-froala-wysiwyg';

const app = createApp(App);          

app.use(VueFroala);
app.mount('#app');

Then add the component to your Vue template.

<template>
  <froala
    id="edit"
    :tag="'textarea'"
    :config="config"
  ></froala>

</template>
<script>
export default {
  name: "App",
  data() {
    return {
      config: {},
    };
  },
};
</script>

You can customize the editor’s toolbar, configure its options, and handle events such as content changes.

Froala also provides extensive documentation and examples to help you get started quickly.

Vue Markdown editor

How to use the Froala Vue WYSIWYG editor as a Vue Markdown editor?

By default, the Froala editor toolbar displays an option for switching between Markdown and the WYSIWYG editor. But in case you want to display the Markdown editor only, you will need to customize the editor as follows.

First, remove the editor toolbar by setting the “toolbarButtons“ API option to an empty array.

config: {
toolbarButtons: [""],
}

Then, on the initialized API event, toggle to the Markdown editor using the markdown.toggle() API method.

    config: {
        toolbarButtons: [""],
        events: {
          initialized: function () {
            // Do something here.
            // this is the editor instance.
            if (!this.markdown.isEnabled()) this.markdown.toggle();
          },
        },
      },

By doing this, you have integrated Froala into our app as a Vue Markdown editor.

Conclusion

Froala is a powerful Vue WYSIWYG editor. Using its Markdown plugin, you can allow users to create well-formatted content using Markdown syntax. Froala supports both WYSIWYG and Markdown editing modes, providing users with flexibility. Froala V4.1 supports Vue 3 out of the box, making it easy to integrate into your Vue app. You can install the Froala Vue package and import the Froala Vue WYSIWYG editor component to get started. The toolbar can be customized to display only the Markdown editor option. With Froala, you can create a user-friendly and efficient editing experience for your Vue app.

See a working example.

useState Hook: Manage Froala React WYSIWYG Editor State

React WYSIWYG Editor

React has evolved to make state management and side effects efficient and expressive. One significant addition to React is the hooks, which allow functional components to manage state and side effects traditionally associated with class components.

In this article, we will explain a basic introduction to React Hooks, with a focus on the “useState“.

Additionally,  Using the “useState” hook, we will show how the Froala React WYSIWYG editor can manage its state and dynamically display the editor changes.

React WYSIWYG editor

React Hooks Overview

Before the hooks, state and lifecycle methods were exclusive to class components.

Hooks were introduced in React to enable functional components to manage local state and other React features without the need for class components. They provide a concise way to handle stateful logic.

The useState is a fundamental hook used for adding state to functional components. It allows you to declare state variables in functional components, making them dynamic.

The basic syntax for “useState” is:

const [state, setState] = useState(initialState);

Here, state is the current state value, and setState is a function that allows you to update the state. The “initialState” is the initial value of the state variable.

Integrating Froala React WYSIWYG Editor

Now, let’s explore how to integrate the Froala with React and the “useState” hook.

The Froala React WYSIWYG editor is a powerful WYSIWYG editor that allows users to easily create rich content. First, install the necessary packages on your React project:

npm install react-froala-wysiwyg --save

Next, create a new React component and import the required dependencies on the “App.js” file:

import React, { useState } from 'react';

import FroalaEditorComponent from 'react-froala-wysiwyg';

import FroalaEditorView from 'react-froala-wysiwyg';

import 'froala-editor/css/froala_style.min.css';

import 'froala-editor/css/froala_editor.pkgd.min.css';

import 'froala-editor/js/plugins.pkgd.min.js';
  1. React and useState are imported from the ‘react’ library. useState is a React hook used for managing state in functional components.
  2. FroalaEditorComponent and FroalaEditorView are components provided by the ‘react-froala-wysiwyg’ package. They are used for integrating the Froala WYSIWYG editor into a React application.
  3. This code imports the styles and scripts for the Froala WYSIWYG editor. These include CSS files for styling and a packaged JavaScript file (plugins.pkgd.min.js) that contains bundled plugins for the editor.

Now, let’s use the “useState” hook to manage the editor’s content:

function App() {

  const [model,setModel] = useState("Example Set");

  const handleModelChange= (event)=>{

    setModel(event)

  }

  return (

    <div className="App">

      <FroalaEditorComponent 

        tag='textarea'

        onModelChange={handleModelChange}

      />

      <FroalaEditorView

        model={model}

    />

    </div>

  );

}

export default App;
  1. The component uses the useState hook to define a state variable named model with an initial value of “Example Set”. This state will hold the content of the Froala editor.
  2. The handleModelChange function is a callback function that will be called when the content of the Froala editor changes.
  3. Inside the function, it updates the model state using setModel(event), effectively updating the content of the editor.
  4. The return statement renders JSX for the component.
  5. The component is wrapped in a div with the class name “App”.
  6. FroalaEditorComponent is rendered with a textarea as the underlying HTML tag. The onModelChange prop is set to the handleModelChange callback function.
  7. FroalaEditorView is rendered with the model prop set to the model state. This component is used to display the content of the Froala editor.
  8. The App component is exported as the default export of the module, making it available for use in other parts of the application.

Maneging Froala React WYSIWYG editor using useState hook

In this example, we’ve created a React component named App. It uses the “FroalaEditorComponent” for editing and the “FroalaEditorView” for displaying the content.

The model state variable is used to manage the content of the editor.

When the content changes, the “handleModelChange” function is called. It updates the model state and triggers a re-render with the new content.

This integration demonstrates how the “useState” hook can manage the state of the Froala. It’s used in a React functional component.

Conclusion

React hooks have upgraded how developers manage state in functional components. The “useState” hook, in particular, is a key part of this upgrade.

Using hooks provides a more concise and readable syntax. It also makes it easier to work with stateful logic in functional components.

Integrating Froala with React enhances the development experience. It allows for seamless content creation and management within your applications. You can manage the editor’s state using the “useState” hook. It enables dynamic creation.

As you explore React hooks and their integration with libraries like Froala React WYSIWYG editor, you’ll find that the combination of these lets you easily build feature-rich web applications.

Building a Support System Using Laravel PHP Framework and Froala HTML Editor Software – Part 1

Laravel support system

Laravel, a popular PHP framework, provides a robust and efficient platform for building web applications. It offers various features and tools to make development easier and faster.

We will use Laravel and the Froala Rich-text editor to create a comprehensive support system for your web application. In this series of tutorials, we will cover how to set up the Laravel project, integrate the Froala editor, save data to a MySQL database, manage support tickets, and more. Let’s dive in and start building!

What should you expect to learn from this tutorial?

This series of articles will include:

In this article, we will create a page with a form that lets users submit requests to the support team. We will integrate the Froala editor to support rich text requests. Finally, we will store the submitted data in the MYSQL database.

The second article will explain how to configure the Froala Editor to upload images and files and how to store them on our PHP server. We may cover this topic over multiple articles.

In the last article, we will create a page for the support team to view all submitted requests. They can access these requests from that page and modify, update, or delete them.

Prerequisites

In this tutorial, I will use XAMPP as my local PHP development environment. XAMPP includes Apache, MySQL, and PHP, which allows you to set up a local server on localhost to test PHP web applications. You can also use alternatives such as WAMP or LAMP, as long as you install and configure them properly.

Also, make sure you install Composer, a dependency manager for PHP, on your computer.

Create a new Laravel project.

After installing PHP and Composer, open your XAMPP server “htdocs”, and create a new Laravel project in your terminal using the command:

composer create-project laravel/laravel support-app

This command downloads the Laravel framework and creates a new project for you.

Once you create the project, navigate to the project directory using the cd command:

cd support-app

Configure the Project Database

Use your preferred IDE, such as Visual Studio Code, to open the project folder. Open the .env file at the root of your application. Update the database configuration values.

DB_CONNECTION=mysql 

DB_HOST=127.0.0.1 

DB_PORT=3306 

DB_DATABASE=laravel 

DB_USERNAME=root 

DB_PASSWORD=

Setup the Database Tables

Run this command in your terminal to create a migration file for the table that will store the support requests:

php artisan make:migration create_requests_table

This above command creates a new migration file in the database/migrations directory. Open the file and define the requests table schema inside the up function.

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

   Schema::create('requests', function (Blueprint $table) {

     $table->id();

     $table->string('name');

     $table->string('email');

     $table->string('subject');

     $table->text('request');

     $table->timestamps();

  });

}

This will create a table with the following columns:

  • id (auto-incrementing integer)
  • name (string) to store the username
  • email (string) to store the user’s email
  • subject (string) – the subject of the request
  • request (text) – the request details
  • created_at (timestamp)
  • updated_at (timestamp)

Once you have defined the schema, ensure your MySQL server runs and contains a database with the name you specified in the .env file.

Run the following command in your terminal to migrate the database and create the table:

php artisan migrate

This command will execute the migration and create the “requests” table in your database.

The request DB table structure

Create a Support Table Model

Create an Eloquent model to interact with the “requests” table by running the command

php artisan make:model Request -crR

The -crR code instructs Laravel to generate model, controller, and request files for the “request” table.

Create the Request Page

We will add a request page to the homepage. Navigate to resources/views/welcome.blade.php, and replace the existing code with the form code. We will use a Bootstrap form to save time.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Support App.</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">

        <!-- Styles -->
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
    </head>
    <body>
        <div class="container">
            <div class="row justify-content-center">
                <h1 class="col-md-8 my-5 text-center">
                    Welcome To Our Support App
                </h1>
            </div>
            <div class="row justify-content-center">
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header">Submit a Support Request</div>

                        <div class="card-body">
                            <form method="POST" > 
                                @csrf
                                <div class="mb-3">
                                    <label for="name" class="form-label">Full Name</label>
                                    <input type="text" class="form-control" id="name">
                                </div>
                                <div class="mb-3">
                                    <label for="exampleInputEmail1" class="form-label">Email address</label>
                                    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
                                    <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
                                </div>
                                <div class="mb-3">
                                    <label for="subject" class="form-label">Subject</label>
                                    <input type="text" class="form-control" id="subject">
                                </div>

                                <div class="mb-3">
                                    <label for="request" class="form-label">Request Details</label>
                                    <textarea class="form-control" id="request" rows="5"></textarea>
                                </div>

                                <button type="submit" class="btn btn-primary">Submit</button>

                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

The above code creates a basic HTML form for submitting a support request, including input fields for the user’s name, email, subject, and request details.

Open “http://localhost/support-app/public/“ on your browser to see the page in action.

laravel request form

Integrate the Froala WYSIWYG Editor into your Laravel application

Integrate the Froala WYSIWYG Editor into our Laravel application to transform the “More Details“ field into one that accepts rich-text editing, which lets users format their requests with advanced styling and formatting options. In the welcome.blade.php file, perform the following steps

  • Add the Froala stylesheet and scripts to the page.
<link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />

<script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>
  • Initialize the editor by using the constructor function FroalaEditor and pass the ID value of the requested field as the first parameter.
<script>
   new FroalaEditor("#request");
</script>
  • Reload your page to display the Froala rich text editor instead of the request field.

froala integrated in Laravel app.

Customize the Froala Editor

The Froala editor’s API provides powerful customization options. Refer to the documentation to discover options, events, and methods that will help you adapt the editor to your needs. In this tutorial, we will use the toolbarButtons API option to customize the editor’s toolbar buttons.

<script>
   new FroalaEditor("#request", {

       toolbarButtons: [
            ['fontSize', 'bold', 'italic', 'underline', 'strikeThrough'],
            [ 'alignLeft', 'alignCenter', 'alignRight', 'alignJustify','textColor', 'backgroundColor'],
            ['formatOLSimple', 'formatUL', 'insertLink','insertImage','insertFile'],
       ]

    });
</script>

Handle the Form Submission

Create a route for the RequestController in routes/web.php to manage form submissions. Since the RequestController is a resource controller, add the following route definition.

Route::resources(['requests' => App\Http\Controllers\RequestController::class]);

We will use the store method in the RequestController to process the form submission. In the welcome.blade.php file, add the action attribute to the form tag, like:

<form method="POST" action="{{ route('requests.store') }}" >

In the store method, add the following code to save the submitted data to the database:

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StorerequestRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StorerequestRequest $request)
    {
        // Retrieve form data and save it to the database

        $model = new Request;

        $model->name = $request->input('name');
        $model->email = $request->input('email');
        $model->subject = $request->input('subject');
        $model->request = $request->input('request');

        $model->save();

        // Redirect back to the form page with a success message
        return redirect()->back()->with('success', 'Your support request has been submitted successfully.');

    }

Make sure the authorize method in the StorerequestRequest.php file returns true to allow visitors to submit the form.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorerequestRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

    }
}

Now, upon form submission, data will be saved in the database, including content from the Froala editor. Then, it redirects the user back to the form page and displays a success message.

Form Validation

To avoid errors when saving the form data to the database, we need to add validation rules. Update the rules method in the StorerequestRequest class found in the App\Http\Requests namespace.

    public function rules()
    {
        return [
            'name' => 'required',
            'email' => 'required|email',
            'subject' => 'required|max:255',
            'request' => 'required',
        ];
    }

In this example, we added validation rules for the “name”, “email”, “subject”, and “request” fields. The “name” field is mandatory, the “email” must be valid, and both the “subject” and “request” fields must be filled. The “subject” field must not exceed 255 characters.

When an invalid input is submitted via the form, the Laravel blade @error and old methods can be used to identify and display an error message as well as repopulate the form fields with previously entered values. This prevents the user from having to re-enter values incorrectly in the fields without having an error.

Update the code in the welcome.blade.php file like the following

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Support App.</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">

        <!-- Styles -->
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>

        <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />

    </head>
    <body>
        <div class="container">
            <div class="row justify-content-center">
                <h1 class="col-md-8 my-5 text-center">
                    Welcome To Our Support App
                </h1>
            </div>
            <div class="row justify-content-center">
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header">Submit a Support Request</div>

                        <div class="card-body">
                            <form method="POST" action="{{ route('requests.store') }}" >
                                @csrf
                                <div class="mb-3">
                                    <label for="name" class="form-label">Full Name</label>
                                    <input type="text" class="form-control @error('name') is-invalid @enderror" id="name" name="name" value="{{(old('name') ? old('name')  : '')}} ">
                                    @error('name')
                                    <span class="invalid-feedback">
                                            <strong>{{ $errors->first('name') }}</strong>
                                        </span>
                                     @enderror
                                </div>
                                <div class="mb-3">
                                    <label for="email" class="form-label">Email address</label>
                                    <input type="email" class="form-control @error('email') is-invalid @enderror" name="email" id="email" value="{{(old('email') ? old('email')  : '')}} " aria-describedby="emailHelp">
                                    <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
                                    @error('email')
                                    <span class="invalid-feedback">
                                            <strong>{{ $errors->first('email') }}</strong>
                                        </span>
                                     @enderror
                                </div>
                                <div class="mb-3">
                                    <label for="subject" class="form-label">Subject</label>
                                    <input type="text" class="form-control @error('subject') is-invalid @enderror" id="subject" name="subject" value="{{(old('subject') ? old('subject')  : '')}} " >
                                    @error('subject')
                                    <span class="invalid-feedback">
                                            <strong>{{ $errors->first('subject') }}</strong>
                                        </span>
                                     @enderror
                                </div>

                                <div class="mb-3">
                                    <label for="request" class="form-label">Request Details</label>
                                    <textarea class="form-control @error('request') is-invalid @enderror"
                                    id="request" name="request" rows="5">{{(old('request') ? old('request')  : '')}}</textarea>

                                    @error('request')
                                    <span class="invalid-feedback">
                                            <strong>{{ $errors->first('request') }}</strong>
                                        </span>
                                    @enderror
                                </div>

                                <button type="submit" class="btn btn-primary">Submit</button>

                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>

        <script>
            new FroalaEditor("#request", {

                toolbarButtons: [
                    ['fontSize', 'bold', 'italic', 'underline', 'strikeThrough'],
                    [ 'alignLeft', 'alignCenter', 'alignRight', 'alignJustify','textColor', 'backgroundColor'],
                    ['formatOLSimple', 'formatUL', 'insertLink','insertImage','insertFile'],
                ]

            });
        </script>
    </body>
</html>

Once you submit the form, the data will be validated using the specified rules. If validation fails, the user will be returned to the form page with error messages displayed, and the form inputs will be repopulated with the previously entered values.

Form with validation

 

Conclusion

In this tutorial, we explored the powerful combination of Laravel and the Froala Rich-text editor to create a comprehensive support system for web applications. By following this series, you learned how to set up the Laravel project, set up your MySQL database, and integrate the Froala editor. We also implemented form submission handling and form validation.

Utilizing Laravel’s robust features and the flexibility of the Froala editor enhances the user experience, empowers your support team, and streamlines the process of handling support requests.

Stay tuned for the next part of this series where you will learn how to save images uploaded with the Froala Editor and store them on a PHP server. We will use the Froala PHP SDK for a smooth experience.

If you have any questions or need further assistance, leave a comment below. Happy coding!

Mastering Froala Paragraph Styles in an Html Code Writer

Froala Paragraph Styles

Paragraph Styles in a text editor are defined sets of formatting rules that can be applied to paragraphs of text in a document. These styles allow users to format their content by defining how text should appear. The options are font, size, color, spacing, and all typographic elements.

Paragraph Styles are used to keep the formatting consistent in a document for a unified look. Instead of changing each paragraph’s settings, users can use a Paragraph Style to get a pre-set format.

Paragraph Styles mean consistency, efficiency, and customization. They can update the whole document when formatting requirements change.

Modern text editors, including WYSIWYG (What You See Is What You Get) editors and HTML code writers like Froala, provide interfaces for managing Paragraph Styles. Users can access these styles through a dropdown menu or toolbar, making the process friendly.

Froala’s WYSIWYG editor and HTML code writer provides a customizable solution for handling text content. We will explain how to use Froala Paragraph Styles in a React project. This plugin allows you to take the text editing capabilities to the next level with our react rich text editor.

Froala WYSIWYG editor provides a customizable solution for handling text content. We will explain how to use Froala Paragraph Styles in a React project. This plugin allows you to take the text editing capabilities to the next level with our react rich text editor.

Understanding Froala

Froala is a feature-rich and easy-to-use text editor that provides various tools for formatting text, handling images, and managing other multimedia elements. It is highly customizable and can be integrated seamlessly into various web applications. One of the standout features of Froala is its support for Paragraph Styles.

Setting Up Your React Project

To get started, make sure you have Node.js and npm installed on your machine.

Create a new project using the Create React App, or use your existing project if you have one. Open your project in your preferred code editor.

npx create-react-app froala-styles-demo

cd froala-styles-demo

npm start

Installing Froala WYSIWYG Editor

Next, you’ll need to install Froala WYSIWYG Editor. You can do this by running the following command in your project directory:

npm install react-froala-wysiwyg --save

This package provides a React wrapper for the Froala editor, making it easy to integrate into your React application.

Creating a new Froala component on the project

Now, let’s create a simple React component that includes the Froala editor. Use the file App.js.

import './App.css';

import FroalaEditorComponent from "react-froala-wysiwyg";

import "froala-editor/css/froala_style.min.css";

import "froala-editor/css/froala_editor.pkgd.min.css";

import "froala-editor/js/plugins.pkgd.min.js";




function App() {




  let model = '<p><a href="https://froala.com">Froala WYSIWYG Editor</a></p>';

  

  return (

    <div id="froala-editor">

      <h1>Froala</h1>

      <FroalaEditorComponent

        tag="textarea"

        model={model}

        config={{

        }}

      />

    </div>

  )

}

export default App;

Let’s break down the provided React code for the Froala Editor component:

  • import ‘./App.css’; This line imports the CSS styles from the “App.css” file. 
  • import FroalaEditorComponent from “react-froala-wysiwyg”;This line imports the FroalaEditorComponent from the “react-froala-wysiwyg” package.
  • import “froala-editor/css/froala_style.min.css”;

import “froala-editor/css/froala_editor.pkgd.min.css”;

import “froala-editor/js/plugins.pkgd.min.js”;

These lines import plugins for the Froala Editor. The first two lines import CSS styles, and the third line imports the packaged JavaScript plugins for the editor.

  • function App() { – Defines a functional React component named App.
  • let model = ‘<p><a href=”https://froala.com”>Froala WYSIWYG Editor</a></p>’; – Declares a variable named model and assigns it a string containing HTML code.
  •  return (

     <div id=”froala-editor”>

Begins the component’s JSX markup, returning a div element with the id “froala-editor”.

  • <h1>Froala</h1> – Includes an h1 element with the text “Froala”.
  • <FroalaEditorComponent

         tag=”textarea”

         model={model}

         config={{

         }}

       />

Includes the FroalaEditorComponent, configuring it with the tag (“textarea”), initial model content, and an empty configuration object. This is where the Froala Editor will be rendered.

</div> ) } – Closes the JSX markup for the component.

export default App; – Exports the App component as the default export of this module.

 

The standard Froala Editor component has some Paragraph Styles already formatted as gray, bordered, spaced, and uppercase.

  • Gray Style: This style involves setting the text color to gray.
  • Bordered Style: A bordered style allows adding a border around an element.
  • Spaced Style: Adding spacing between elements makes setting margins or padding.
  • Uppercase Style: To make text uppercase, you can use the text-transform property.

Froala Paragraph Styles

Styling Paragraphs with Froala

Now that we have the basic editor set up, let’s explore how to customize Paragraph Styles.

You can customize the appearance of each paragraph style by modifying the Froala configuration. On the config use this code:

      config={{

          paragraphStyles: {

            class1: 'Class 1',

            class2: 'Class 2'

          },

        }}

On the file App.css, use this code:

.class1 {

  text-align: center;

  font-weight: bold;

}

.class2 {

  font-weight: 300;

  font-size: 30px;

}

This code is a set of CSS rules that define styles for HTML elements with specific class names.

  • text-align: center; – This rule centers the text within the element horizontally.
  • font-weight: bold; – This rule makes the text bold.
  • font-weight: 300; – This rule sets the font weight to 300, which is relatively light or normal weight.
  • font-size: 30px; – This rule sets the font size to 30 pixels.

custom Froala Paragraph Styles

Conclusion

In this article, we’ve covered the integration of Froala WYSIWYG Editor into a React project and explored how to implement and customize Paragraph Styles.

With the ability to define custom styles and easily apply them, Froala provides a powerful solution for creating rich text editors in your web applications.

Explore Froala’s extensive documentation for more advanced features and customization options.

The key to mastering Paragraph Styles is experimentation. Play around with the configurations, try different styles, and see how they impact your editor.

Image Management in Express Framework: Froala Node.JS SDK

Froala Node.js SDK

Express framework is a popular web application framework for Node.JS. It provides a simple and minimalistic approach to building web applications. Froala is an advanced WYSIWYG editor for effortless content creation and editing. We discussed the integration between Froala and Express framework before. However, uploading images and files into the Node server needs additional configuration. The Froala Node.js SDK simplifies uploading images and files to Froala in an Express application. With this SDK, you can easily handle image uploads, validate them, store them, and delete them on your server. This makes it incredibly convenient to integrate Froala into your Express application and provide a seamless image-uploading experience for your users.

Throughout this tutorial, we will cover the steps to set up the uploading image process in your Express application using the Froala Node.JS SDK. We will continue from where we left off in the integration article. We recommended reading the integration guide first.

Install Froala Node.JS SDK

You can install the Froala Node.JS SDK by running the following command in your terminal:

npm install wysiwyg-editor-node-sdk

Import the SDK into your Express application after installing it by adding this line of code in the app.js file.

var FroalaEditor = require(__dirname+'/node_modules/wysiwyg-editor-node-sdk/lib/froalaEditor.js');

Configure the Froala Editor

We will need to configure the Froala initialization function to assign the image upload options and events. There are six API options and five events related to this feature.

  • imageUploadParam: is the name of the parameter that contains the image file information in the upload request. The default value is “file” but you can change it to whatever name you want.
  • imageUploadURL: is the URL where the upload request is being made.
  • imageUploadParams: are additional parameters that are passed in the upload request to the server.
  • imageUploadMethod: is the HTTP request type. It is ‘POST’ by default.
  • imageMaxSize: sets the upper limit for image size during uploading.
  • image.beforeUpload: Froala triggers this event before starting the upload request and it can be used to change the upload params or cancel the action.
  • image.uploaded: Froala triggers this event after a successful image upload request, but before inserting the image into the editor.
  • image.inserted: Froala triggers this event after inserting the image into the editor.
  • image.replaced: Froala triggers this event after replacing the image in the editor.
  • image.error: Froala triggers this event if any errors occur during the upload process.

In the “editor.ejs” file, change the initialization method to

var editor = new FroalaEditor("#example", {

imageUploadURL: '/upload_image'

});

The above code will configure the Froala Editor to upload images to the ‘/upload_image’ URL.

Handle the Image Upload Request

We need to define the ‘/upload_image’ route in our Express application to handle the image upload request. It will receive the image file and save it on the server using the FroalaEditor.Image.upload method.

Add the following code to your app.js file:

app.post('/upload_image', function (req, res) {
    // Store image.

    FroalaEditor.Image.upload(req, '/uploads/', function(err, data) {

    // Return data.

    if (err) {

         return res.send(JSON.stringify(err));

     }

     res.send(data);

   });

});

The above code will create a POST route in your Express application at ‘/upload_image’. When this route receives a request, it will use the FroalaEditor.Image.upload method to store the uploaded image in the ‘/uploads/’ directory on the server. If there are any errors during the upload process, it will return the error as a JSON string. Otherwise, it will send the data object containing information about the uploaded image as the response.

Create an “uploads” folder in the root of our Express app to store uploaded images.

Also, add the below code to the “app.js” file to give the server access to the static files in the root directory. This will allow images and files in ‘/uploads/’ to be accessed.

app.use(express.static(__dirname + '/'));

Now, when you upload an image with the Froala Editor, it will be saved in the ‘/uploads/’ directory and accessible through the ‘/uploads/’ URL.

The full app.js code is

var express = require('express');

var FroalaEditor = require(__dirname+'/node_modules/wysiwyg-editor-node-sdk/lib/froalaEditor.js');

var app = express();

// Set EJS as the view engine

app.set('view engine','ejs');

//Froala editor CSS & JS files

app.use('/froalacss',express.static(__dirname+'/node_modules/froala-editor/css/froala_editor.pkgd.min.css'));

app.use('/froalajs',express.static(__dirname+'/node_modules/froala-editor/js/froala_editor.pkgd.min.js'));

//So images can be displayed after stored

app.use(express.static(__dirname + '/'));

// Define routes

app.get('/',(req,res)=>{

  res.render('editor');

});


// Path to upload image.

app.post('/upload_image', function (req, res) {

     // Store image.

     FroalaEditor.Image.upload(req, '/uploads/', function(err, data) {

    // Return data.

    if (err) {

    return res.send(JSON.stringify(err));

    }

    res.send(data);

   });

});

var port = process.env.PORT || 3000;

app.listen(port,()=>console.log('server run at port '+port));

Test the Image Upload Functionality

Now that we have configured the Froala Editor and created a route to handle the image upload request, we can test the functionality. Start your Express application by running the following command:

node app.js

Once your application is running, open http://localhost:3000/ and start working with the editor. Upload an image using the editor and see if it gets stored in the “uploads” directory. You should be able to successfully upload and store images using the Froala Editor in your Express application.

Upload image using Froala Node.js SDK

Image Validation

To further enhance the image upload functionality, you can add validation to ensure that only specific image types and sizes are allowed. Froala Node.JS SDK simplifies the image validation process.

Using the SDK, you can pass an object with the validation roles at the third parameter of the FroalaEditor.Image.upload method. The supported validation rules are:

  • allowedExts: Contains the allowed image extensions
  • allowedMimeTypes: Contains the allowed mime types

In the following code, we altered the “/upload_image“ route handler to allow only JPEG and JPG image types to be uploaded through Froala editor

// Path to upload image.

app.post('/upload_image', function (req, res) {

var options = {

  validation: {

   'allowedExts': [ 'jpeg', 'jpg'],

   'allowedMimeTypes': [ 'image/jpeg', 'image/pjpeg']

  }

}

// Store image.

FroalaEditor.Image.upload(req, '/uploads/', options, function(err, data) {

   // Return data.

   if (err) {

     return res.send(JSON.stringify(err));

   }

   res.send(data);

  });

});

However, if you want to perform other validation, it is possible too. You can pass a custom method instead of the validation object with filePath, mimetype, and callback parameters. This gives you full control over what types of images you want to store on disk. Learn how the custom validation works.

Deleting Images with Froala Node.JS SDK

The Froala Node.JS SDK also simplifies deleting images on the editor from the server. When You click on an image in the editor, a pop-up appears. On that pop-up, there is a delete image button. When a user clicks on that button, the editor triggers two events:  froalaEditor.image.beforeRemove and froalaEditor.image.removed. You can use either option to delete the image from the server, but it’s recommended to use the second one to ensure that the image is removed from the editable area.

In the froalaEditor.image.removed event, we will send a request to the server to delete the image. In the “app.js” you will need to define a route to handle the delete request. This handler will use the FroalaEditor.Image.delete() method from the Node.JS SDK to remove the image from the server.

Unlocking the other capabilities of the Froala Node.JS SDK

The Froala Node.JS SDK will help you also store images on the Amazon S3 bucket, display the uploaded images on Froala Image Manager, and handle other files on your Node.JS server.

Streamlining the editor Image handling in Express with Froala Node.JS SDK

With these configurations and code in place, you have successfully simplified uploading images to Froala Editor in an Express framework application using the Froala Node.js SDK. The Froala Node.JS SDK provides a convenient way to handle image uploads, validate them, and store them on your server. This integration allows you to provide a seamless image-uploading experience for your users. You can now continue building your Express application with the enhanced functionality of Froala Editor.

Angular CMS Development: Integrate Froala WYSIWYG Editor

Angular CMS

With a Content Management System (CMS), you can easily create, modify, manage, and publish content in a user-friendly way. Starting with HTML to add text, forms, images, navigation bars, and other essential website components is straightforward. That’s why having a secure, intelligent, fast, and robust HTML code writer is crucial.

Froala, the next-generation WYSIWYG HTML code writer, has become a go-to solution for users, enabling them to shape content without diving into intricate code. This editor seamlessly integrates with any framework like React, Vue, Angular, etc., providing rich text editing capabilities for your CMS.

This article will explore how you can use the WYSIWYG HTML code writer to build a feature-rich CMS using Angular and integrate Froala’s HTML code writer for a modern design and more customizable experience.

What is a Content Management System (CMS)?

A CMS is software that helps you create, organize, and modify website content, such as text, images, and videos, without having any technical knowledge. Moreover, it provides tools for user management and collaborative workflows and offers features for version controls and scheduling content publication. Some Popular CMS systems include WordPress, Joomla, Drupal, etc.

HTML Code Writer For Seamless CMS Development

The role of a WYSIWYG HTML editor in CMS development is paramount. WYSIWYG, or What You See Is What You Get, editors are instrumental in simplifying content creation within a CMS. An intuitive WYSIWYG HTML editor is a crucial component of a CMS that allows seamless content creation, enhances user experience, and enables efficient content management without requiring coding skills.

The following section will explore building a CMS using Froala, a WYSIWYG HTML editor. We are choosing Froala for CMS development because its developer-friendly feature makes it easy to integrate with multiple frameworks, including angular, and allows developers to create and modify content with more control.

How to Build a CMS with Froala using Angular?

Make your CMS development easier, flexible, robust, and faster by integrating Froala with Angular. This powerful combination offers a sophisticated platform for building a feature-rich Content Management System, blending Froala’s intuitive design with the robust capabilities of Angular for a seamless development experience with our angular rich text editor.

Prerequisites

Before starting, you will need

  • Node.js and npm: Visit Node.js site to get the latest version of Node.js. Note that npm comes as a part of the package with node.js.
  • Angular CLI: Launch the command prompt of the terminal to set up the Angular CLI on your machine. Run the command below:
npm install -g @angular/cli
  • Visual Studio Code: A text editor for building and compiling the code.

Step 1: Setup the Angular Project

First of all, open the terminal in the Visual Studio Code and set up your AngularJS project by running the following command.

ng new my-app

Angular project

After that, navigate to your app folder.

cd my-app

Step 2: Install and Integrate the Froala Editor

Now, let’s install the Froala Editor.

npm install angular-froala-wysiwyg --save

Once it’s installed, you need to import the Froala Editor module into your Angular module. Open ‘src/app/app.module.ts’ file and add the following code.

import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';

@NgModule({
declarations: [
// your components here
],
imports: [
FroalaEditorModule.forRoot(),
FroalaViewModule.forRoot(),
// other modules here
],
bootstrap: [AppComponent],
})
export class AppModule {}

Step 3: Create a Content Management System (CMS)

Here we will create a content management system using AngularJS and Flora with the help of multiple components.

Create an Editor Component

In the terminal of VS Code, run the following to create an editor component. This will create a new folder named ‘editor’ with the necessary files.

ng generate component editor

Angular editor component

Open ‘src/app/editor/editor.component.html’ and add the Froala Editor.

<div [froalaEditor]></div>

Now, in your ‘src/app/app.component.html’ file, replace the existing content with:

<header>

<div class="header-content">

<h1>Content Management System</h1></div>

</header>

<app-editor></app-editor>

Add the following design code for the header in the ‘src/app/app.component.css’ file.

header {
background-color: #f0f0f0; /* Add your desired background color */
padding: 10px;
}.header-content {
text-align: center;
}h1 {
margin: 0;
}

 Create a Service for Data Management

Now, let’s add the ability to save the content entered in the Froala Editor. We’ll create a service to handle data management. First, create a new service.

ng generate service content

This will create a file named ‘content.service.ts’ in the src/app folder.

Angular service

Open ‘src/app/content.service.ts’ and add the following:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class ContentService {
  private contentSubject = new BehaviorSubject<string>('');

  getContent() {
    return this.contentSubject.asObservable();
  }

  updateContent(content: string) {
    this.contentSubject.next(content);
  }
}

 Modify Editor Component

Now, let’s modify our ‘editor.component.ts’ to use this service.

import { Component, OnInit } from '@angular/core';
import { ContentService } from '../content.service';

@Component({
  selector: 'app-editor',
  templateUrl: './editor.component.html',
  styleUrls: ['./editor.component.css'],
})
export class EditorComponent implements OnInit {
  
  content: string = '';
  
  constructor(private contentService: ContentService) {}

  ngOnInit() {}

  onContentChanged(content: string) {
    this.contentService.updateContent(content);
  }
}

Update ‘editor.component.html’ to pass the content to the service when it changes:

<div [froalaEditor] [(froalaModel)]="content" (froalaModelChange)="onContentChanged($event)"></div>

 Create a Viewer Component

Now, let’s create a new component to display the saved content. Run:

ng generate component viewer

Angular Viewer

Open ‘src/app/viewer/viewer.component.ts’ and add the following code.

import { Component, OnInit } from '@angular/core';
import { ContentService } from '../content.service';

@Component({
  selector: 'app-viewer',
  templateUrl: './viewer.component.html',
  styleUrls: ['./viewer.component.css'],
})
export class ViewerComponent implements OnInit {
  content: string = '';

  constructor(private contentService: ContentService) {}

  ngOnInit() {
    this.contentService.getContent().subscribe((content) => {
      this.content = content;
    });
  }
}

Update ‘viewer.component.html’ to display the content.

<div [froalaView]="content"></div>

Now, update ‘app.component.html’ to include both the editor and the viewer.

<header>
  <div class="header-content">
  <h1>Content Management System</h1></div>
</header>

<app-editor></app-editor>
<app-viewer></app-viewer>

Step 4: Run the CMS Application

Start your Angular development server using the command:

ng serve

Now go to http://localhost:4200 and check your application running on the following port.

Froala runing in Angular

The CMS application has been successfully built and running.

Step 5: Test the Data Management on CMS

To test the data storage and display on the screen using the viewer component, we have to pass some text in the text field shown above in the CMS dashboard. Let’s write some text and test.

Angular WYSIWYG editor

As the data is displayed in the screen below the dashboard, the CMS has been successfully tested and displaying the correct data.

Make CMS Development Fast, Robust, and Secure with Froala WYSIWYG HTML Editor

Froala is a WYSIWYG HTML editor that, when combined with Angular, enables seamless CMS development. This collaboration, combining Froala’s user-friendly interface and rich features with Angular’s capabilities, provides developers with a toolkit for crafting efficient and customizable CMS solutions.

With Froala, you can format text, put in images, and include different things easily. Your CMS becomes more than just plain text—it can have lists, pictures, and more. You can adjust it to fit what you need for your CMS, making it simple and good for users.

Get started with Froala today for seamless CMS development!

Learn to Integrate Froala Visual HTML Editor into Your NodeJS App

Froala in NodeJS and Express

NodeJS is a popular runtime environment that allows you to run JavaScript on the server side. It offers various frameworks to build web applications, and one of the most popular ones is Express. In this tutorial, we will learn how to integrate Froala, a powerful visual HTML editor, into a NodeJS application built with Express. Froala provides an easy-to-use interface for users to create and edit rich text content.

Before diving in, we assume you have a working knowledge of:

  • JavaScript
  • NodeJS and npm
  • Express Framework
  • How to use the terminal/command line

Create a new NodeJS app

To create a new NodeJS app, open your terminal or command line and navigate to the desired directory where you want to create your app. Then, run the following command:

npm init

This will initialize a new NodeJS project inside the selected directory. You will be prompted with some questions for filling the `package.json` file. Accept the default values except for “main”, which we will set to “app.js”.

Install Dependencies

Next, we need to install the Express framework, Embedded JavaScript templates (EJS), and Froala WYSIWYG editor

Run the following command:

$ npm install froala-editor ejs express

This will install the required dependencies for our NodeJS application. Once the installation is complete, we can proceed to integrate Froala visual html editor into our Express application.

Set up the Express application

First, let’s create a new file named “app.js” in the root directory of our project. This file will serve as the entry point for our Express application.

Open “app.js” in your preferred text editor and add the following code:

var express = require('express');

var app = express();

// Set EJS as the view engine
app.set('view engine','ejs');

//Froala editor CSS & JS files
app.use('/froalacss',express.static(__dirname+'/node_modules/froala-editor/css/froala_editor.pkgd.min.css'));
app.use('/froalajs',express.static(__dirname+'/node_modules/froala-editor/js/froala_editor.pkgd.min.js'));

// Define routes 
app.get('/',(req,res)=>{
 res.render('editor');
});

var port = process.env.PORT || 3000;
app.listen(port,()=>console.log('server run at port '+port));

In the above file, we first import the Express framework and an instance of it using the `express()` function.

Next, we set EJS as the view engine by using the `app.set()` method.

Then, we use the `app.use()` method to serve the Froala editor CSS and JS files as static files.

After that, we define a route for the root URL (“/”) and render the “editor” view using the `res.render()` method.

Finally, we set the port for the server to listen on and start the server using the `app.listen()` method.

Create the views

Next, let’s create the views for our application. Inside the root directory of your project, create a new directory called “views”. Inside the “views” directory, create a new file called “editor.ejs”.

Open “editor.ejs” in your preferred text editor and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="/froalacss">
    <script src="/froalajs"></script>
    <title>Document</title>
</head>
<body>
    <h1>Froala Editor</h1>
    <textarea id="example"></textarea>
    <script>
            var editor = new FroalaEditor("#example");
     </script>
</body>
</html>

In the above file, we create a basic HTML structure with a title and a heading. We include the Froala editor CSS file and the Froala editor JS file using the `<link>` and `<script>` tags respectively. Inside the body, we create a textarea element with the id “example”. Finally, we initialize the Froala editor by creating a new instance of the FroalaEditor class and passing in the textarea element’s id as a parameter.

Test the application

To test the application, run the following command in your terminal or command line:

$ node app.js

This will start the server and your application will be accessible at `http://localhost:3000\`.

You should be able to see the Froala Editor interface with a textarea where you can create and edit rich text content. You can test the functionality of the editor by typing in the textarea and applying various formatting options provided by Froala.

Congratulations! You have successfully integrated Froala into your NodeJS application built with Express.

Customize The Froala Editor

One benefit of using Froala editor rather than other WYSIWYG editors is its extensive customization options. Froala allows you to tailor the editor to fit the specific needs of your application.

To customize the Froala editor, you can modify the initialization code in the “editor.ejs” file. The FroalaEditor class accepts an options object as a parameter, where you can specify various configuration settings.

For example, you can customize the toolbar buttons by setting the “toolbarButtons” property. You can choose which buttons to include in the toolbar and in what order they should appear.

Here’s an example of how you can customize the toolbar buttons:

            var editor = new FroalaEditor("#example", {

             toolbarButtons: ['bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript', 'fontFamily', 'fontSize', 'color', 'backgroundColor', 'align', 'formatOL', 'formatUL', 'indent', 'outdent', 'insertImage', 'insertLink', 'insertTable', 'insertVideo', 'undo', 'redo']

              });

In the above example, we set the “toolbarButtons” property to an array of button names. This will customize the toolbar to only include the specified buttons.

You can explore the Froala documentation to find more customization options and configure the editor according to your requirements.

froala nodejs sdk

Uploading Images, Videos, and Files

To upload images, videos, and files using Froala, we need to make some changes to our existing code. For simpification Froala provides NodeJS SDK to handle file uploads. We will cover how to use the Froala NodeJS SDK in another article.

Do I need to Secure the Froala integration?

Froala WYSIWYG HTML Editor has robust XSS attack prevention. Generally, you won’t have to worry at all about this, however, additional server-side checks are recommended.

Conclusion

We have successfully integrated the Froala editor into our NodeJS application built with Express. We have created the necessary files and views, tested the application, and explored customization options for the editor. We have also discussed the possibility of uploading images, videos, and files using the Froala NodeJS SDK. The editor also provides a strong defense against XSS attacks, ensuring the security of your application. So why wait? Start integrating Froala into your NodeJS application today and take your content editing experience to the next level.

Improve React Project Engagement: Custom Emoticons with HTML Editor Software

Froala custom emoticons

In 2023, having an engaging user interface is crucial for keeping people interested. One effective way to enhance user experience is by incorporating emoticons into your application.

Emoticons, or emojis, have evolved from being mere embellishments to essential elements in development. They play a significant role in enhancing communication across platforms.

Emoticons are important because they help us express ourselves and engage users more effectively. They personalize messages, making communication more relatable and engaging.

Additionally, emoticons serve as a universal language, boosting branding efforts by adding a visual element to text, making content more compelling.

They also contribute to storytelling by conveying emotions and context within limited space. Integrating emoticons using advanced HTML editor software can significantly elevate your application’s user interface and overall experience.

The Froala WYSIWYG editor lets you do this with its Custom Emoticons feature. In the blog post, we will explore how to integrate Froala Custom Emoticons into a React project with our versatile react rich text editor.

Froala HTML Editor Software Custom Emoticons

Take a moment to see how Froala Custom Emoticons can help your application. Froala is a tool that helps developers make advanced text editors for web apps.

Users can add their own emoticons or emojis using the Custom Emoticons feature, expanding the editor’s capabilities.

Users can use Custom Emoticons to add their own personal touch to messages, instead of using the standard emojis.

Prerequisites

Before we start, make sure you have the following prerequisites installed:

  • Node.js and npm (Node Package Manager): Ensure that you have Node.js installed on your machine.
  • Create React App: Install Create React App globally using the following command:
npm install -g create-react-app

Now that we have the prerequisites in place, let’s proceed with the integration.

Setting Up a React Project

To get started, create a new React project using the Create React App. Open your terminal and run the commands:

npx create-react-app froala-custom-emoticons-demo

cd froala-custom-emoticons-demo

This will create a new React project named froala-custom-emoticons-demo and navigate into its directory.

Installing Froala Editor

To use Froala Custom Emoticons in our React project, we need to install the Froala Editor package. In your project directory, run the command:

npm install react-froala-wysiwyg --save

This package provides a React wrapper for the Froala Editor, making it easy to integrate into our application.

Integrating Froala Editor

Now that we have the Froala Editor installed, let’s integrate it into our React project. Open the “src/App.js” file in your code editor and replace its contents with the following code:

import './App.css';

import FroalaEditorComponent from "react-froala-wysiwyg";

import "froala-editor/css/froala_style.min.css";

import "froala-editor/css/froala_editor.pkgd.min.css";

import "froala-editor/js/plugins.pkgd.min.js";

function App() {

  let model = '<p><a href="https://froala.com">Froala WYSIWYG Editor</a></p>';

  return (

    <div id="froala-editor">

      <h1>Froala</h1>

      <FroalaEditorComponent

        tag="textarea"

        model={model}

        config={{

        }}

      />

    </div>

  )

}

export default App;

 

  1. The import App.css statement imports the styles specific to the App component.
  2. FroalaEditorComponent is a React component provided by the “react-froala-wysiwyg” package.
  3. The next 3 lines are about importing the Froala editor styles and plugins.
  4. The App function is a functional React component.
  5. The model variable contains the initial content of the Froala editor. It’s a simple HTML string with a link.
  6. Inside the return statement, there’s a div with the id “froala-editor” and an h1 element with the text “Froala.”
  7. The FroalaEditorComponent is used to render the Froala editor. It is configured to use a textarea as its underlying element (tag=”textarea”), and the initial content is set using the model prop.
  8. The App component is exported as the default export of this module.

emoticons in React

Using Custom Emoticons in Froala Editor

Froala Editor provides flexibility in customizing the display of emoticons. The following code must be put on the config part.

In the toolbarButtons define the button emoticons.

You can control how many emoticons show up in each row of the emoticons menu by using the emoticonsStep property in the FroalaEditor component’s config prop.

The emotionsSet allows you to personalize the emotions displayed.

       toolbarButtons: ["emoticons"],

          emoticonsStep: 4,

          emoticonsSet: [{

            id: 'people',

            name: 'Smileys & People',

            code: '1f600',

            emoticons: [

             { code: '1f600', desc: 'Grinning face' },

             { code: '1f601', desc: 'Grinning face with smiling eyes' },

             { code: '1f602', desc: 'Face with tears of joy' },

             { code: '1f603', desc: 'Smiling face with open mouth' },

             { code: '1f604', desc: 'Smiling face with open mouth and smiling eyes' },

            { code: '1f605', desc: 'Smiling face with open mouth and cold sweat' },

             { code: '1f606', desc: 'Smiling face with open mouth and tightly-closed eyes' },

       { code: '1f607', desc: 'Smiling face with halo' }

            ]

            }, {

            id: 'nature',

            name: 'Animals & Nature',

            code: '1F435',

            emoticons: [

              { code: '1F412', desc: 'Monkey' },

              { code: '1F415', desc: 'Dog' },

              { code: '1F429', desc: 'Poodle' },

              { code: '1F408', desc: 'Cat' },

              { code: '1F405', desc: 'Tiger' },

              { code: '1F406', desc: 'Leopard' },

              { code: '1F40E', desc: 'Horse' },

              { code: '1F402', desc: 'Ox' },

              { code: '1F403', desc: 'Water Buffalo' },

            ]

          }]

        }}

Here’s an explanation:

  1. toolbarButtons: [“emoticons”]: This adds an “emoticons” button to the toolbar, indicating that users can interact with emoticons.
  2. emoticonsStep: 4: This is related to some intervals for emoticons.
  3. emoticonsSet: An array containing sets of emoticons. In this case, there are two sets: “Smileys & People” and “Animals & Nature”.
  4. For “Smileys & People” (id: ‘people’):
    • code: ‘1f600’: Identifier for this set.
    • emoticons: An array of objects, each representing an emoticon with a code (e.g., ‘1f600’) and a description of the emoji (‘Grinning face’, ‘Grinning face with smiling eyes’, ‘Face with tears of joy’, ‘Smiling face with open mouth’, ‘Smiling face with open mouth and smiling eyes’, ‘Smiling face with open mouth and cold sweat’, ‘Smiling face with open mouth and tightly-closed eyes’, ‘Smiling face with halo’).
  1. For “Animals & Nature” (id: ‘nature’):
    • code: ‘1F435’: Another identifier for this set.
    • emoticons: Array of objects, each representing an animal or nature-related emoticon (‘Monkey’, ‘Dog’, ‘Poodle’, ‘Cat’, ‘Tiger’, ‘Leopard’, ‘Horse’, ‘Ox’, ‘Water Buffalo’).

Running the React App

Now that we’ve set up the Froala Editor in our React project, let’s run the application and see our Custom Emoticons in action. In your terminal, run the following command:

npm start

This will start the development server, and you can view your React app by navigating to http://localhost:3000 in your web browser.

Add emoticons in React

Conclusion

This article shows how to add Froala Custom Emoticons to a React project. It makes communication more expressive and personal.

You can make a text editor with lots of features. Users can add their own emoticons, which makes the app more fun and interactive.

Froala Editor has many features for developers, like Custom Emoticons.

As you work on your React project, try using Froala Editor to improve your web app’s features and user experience.

Creating a Rich Text Form in NextJS Using an Online JavaScript Editor

NextJS rich text forms

NextJS is a powerful React framework that enables developers to build server-side rendered and static web applications with ease. An online JavaScript editor, like Froala, is a highly customizable, rich-text editor for web and mobile applications. When these two powerful tools are combined, they provide an efficient way to create dynamic, rich-text forms for your web application. In this simple tutorial, we will walk you through building a Contact Us form in NextJS, finishing with the integration of an online JavaScript editor for users to craft attractive, organized messages. Using an online JavaScript editor ensures a seamless, user-friendly experience, enhancing the overall functionality and aesthetics of your web application.

We will cover the configuration and customization of your rich-text form.

Create a new NextJS project

To create a new NextJS application, run the following NPM command:

npx create-next-app@latest

install nextJS

Answer the prompted questions like:

√ What is your project named? contact-form

√ Would you like to use TypeScript? Yes

√ Would you like to use ESLint? Yes

√ Would you like to use Tailwind CSS? Yes

√ Would you like to use src/ directory? Yes

√ Would you like to use App Router? (recommended) Yes

√ Would you like to customize the default import alias (@/*)? … No

This will scaffold a new NextJS project named “contact-form“ in your current directory. Once created, navigate into your new project by running:

cd contact-form

Creating a simple contact form

In this tutorial, we will use the react-hook-form for creating our form component. The react-hook-form is a lightweight, performant form library for React that leverages the use of hooks. It’s easy to use, requires little boilerplate code, and includes features such as form validation and error handling built right in.

To install react-hook-form, run the following NPM command:

npm install react-hook-form

After installing react-hook-form, let’s create our form component.

  • Create the `components` directory, if it doesn’t exist.
  • Create a new component file named `contact.tsx` Inside the `components` directory.
  • Open the `contact.tsx` using your preferred IDE to start editing it.
  • Since this component will run on the client side not the server side, add the following on the first line:
'use client';
  • react-hook-form provides a form builder that you can use to easily create your form and it will display the component code on the right.

form builder

Use this builder to build the form fields you like to have on your page, then copy the code in the `contact.tsx` file we created. Note that the form code doesn’t have a style for the form, so we will add some Tailwind CSS classes to make the form visually appealing. After all, this how our Contact component code looks like.

'use client';

import React from 'react';
import { useForm } from 'react-hook-form';.

export default function Contact() {

  const { register, handleSubmit, formState: { errors } } = useForm();

  const onSubmit = (data: any) => console.log(data);

  console.log(errors);

  
  return (

    <form

    className="w-full max-w-5xl"

    onSubmit={handleSubmit(onSubmit)}>

      <div className='mb-5'>

        <label

          htmlFor='name'

          className='mb-3 block text-base font-medium text-black'

        >

          Full Name

        </label>

        <input

          type='text'

          placeholder='Full Name'

          className='w-full rounded-md border border-gray-300 bg-white py-3 px-6 text-base font-medium text-gray-700 outline-none focus:border-purple-500 focus:shadow-md'

          {...register('name', { required: true })}

        />

      </div>

      <div className='mb-5'>

        <label

          htmlFor='email'

          className='mb-3 block text-base font-medium text-black'

        >

          Email Address

        </label>

        <input

          type='email'

          placeholder='[email protected]'

          className='w-full rounded-md border border-gray-300 bg-white py-3 px-6 text-base font-medium text-gray-700 outline-none focus:border-purple-500 focus:shadow-md'

          {...register('email', { required: true })}

        />

      </div>

      <div className='mb-5'>

        <label

          htmlFor='Mobile number'

          className='mb-3 block text-base font-medium text-black'

        >

          Mobile number

        </label>

      <input 

       type="tel"

       placeholder="Mobile number"

       className='w-full rounded-md border border-gray-300 bg-white py-3 px-6 text-base font-medium text-gray-700 outline-none focus:border-purple-500 focus:shadow-md'

        {...register("Mobile number", {required: true, minLength: 6, maxLength: 12})}

      />

      </div>

      <div className='mb-5'>

        <label

          htmlFor='message'

          className='mb-3 block text-base font-medium text-black'

        >

          Message

        </label>

        <textarea

          rows={5}

          placeholder='Type your message'

          className='w-full resize-none rounded-md border border-gray-300 bg-white py-3 px-6 text-base font-medium text-gray-700 outline-none focus:border-purple-500 focus:shadow-md'

          {...register('message', { required: true })}

        ></textarea>

      </div>

      <div>

        <button className='hover:shadow-form rounded-md bg-white border py-3 px-8 text-base font-semibold outline-none text-gray-700'>    

          Submit

        </button>

      </div>

    </form>

  );

}

As you can see on the above code, the Contact component will handle the form submission at the moment.

When a user submits the form, the validation starts. If there is a validation error, the errors will be logged on the console. If there are no validation errors, the input data will also be logged on the console. In a real-world application, we will need to change this behavior so the data is sent to the site administrator.

Test The Form

Display the Form in our application

To display the form on the homepage, let’s replace the code on “app/page.tsx” with the following code

import Contact from '@/components/contact';

export default function Home() {

return (

<main className="flex min-h-screen flex-col items-center justify-between p-24">

<Contact />

</main>

)

}

The above code imports the `Contact` component that we just created and renders it in the `Home` component. The Home component is the main component that is displayed when the user lands on the homepage. The `Contact` component is wrapped in the `main` tag, which is styled using Tailwind CSS to center the form on the page.

Run the NextJS app

Now, run the application using the following command:

npm run dev

This will start the Next.js development server.

Result

NextJS form

Open your web browser and navigate to `localhost:3000`. You should now see the contact form on your homepage. Open the browser console, and try submitting the form with different inputs to test the validation. If the validation fails, you will see the error messages logged in the console. If the form is submitted successfully, you will see the form data logged in the console.

The next step will be enhancing the message field to support rich text.

Enhance React Forms by Integrate Froala Rich-text

Now that our basic contact form is working as expected, we can enhance it to enable users to write rich text messages. For this, we will use the Froala WYSIWYG editor. It offers a wide range of features, including text formatting, image and video insertion, tables, and more. Moreover, it is easily integrated with NextJS since it already has a ready React rich-text editor component.

Install Froala Editor React component

First, install the Froala Editor package in your Next.js application using the following command:

npm install react-froala-wysiwyg --save

Import Froala Editor Component and stylesheets

inside “contact.tsx” file, and add

import 'froala-editor/css/froala_style.min.css';

import 'froala-editor/css/froala_editor.pkgd.min.css';

import FroalaEditorComponent from 'react-froala-wysiwyg';

Display the Froala React rich-text editor

Inside the return statement, add the Froala component after the Message field so it appears under it and before the submit button. Update the code as follows:

return (

<form

className="w-full max-w-5xl"

onSubmit={handleSubmit(onSubmit)}

>

<div className='mb-5'>

<label

htmlFor='name'

className='mb-3 block text-base font-medium text-black'

>

Full Name

</label>

<input

type='text'

placeholder='Full Name'

className='w-full rounded-md border border-gray-300 bg-white py-3 px-6 text-base font-medium text-gray-700 outline-none focus:border-purple-500 focus:shadow-md'

{...register('name', { required: true })}

/>

</div>

<div className='mb-5'>

<label

htmlFor='email'

className='mb-3 block text-base font-medium text-black'

>

Email Address

</label>

<input

type='email'

placeholder='[email protected]'

className='w-full rounded-md border border-gray-300 bg-white py-3 px-6 text-base font-medium text-gray-700 outline-none focus:border-purple-500 focus:shadow-md'

{...register('email', { required: true })}

/>

</div>

<div className='mb-5'>

<label

htmlFor='Mobile number'

className='mb-3 block text-base font-medium text-black'

>

Mobile number

</label>

<input

type="tel"

placeholder="Mobile number"

className='w-full rounded-md border border-gray-300 bg-white py-3 px-6 text-base font-medium text-gray-700 outline-none focus:border-purple-500 focus:shadow-md'

{...register("Mobile number", {required: true, minLength: 6, maxLength: 12})}

/>

</div>

<div className='mb-5'>

<label

htmlFor='message'

className='mb-3 block text-base font-medium text-black'

>

Message

</label>

<textarea

rows={5}

placeholder='Type your message'

className='w-full rounded-md border border-gray-300 bg-white py-3 px-6 text-base font-medium text-gray-700 outline-none focus:border-purple-500 focus:shadow-md'

{...register('message', { required: true })}

>

</textarea>

</div>

<div className="mb-5">

<FroalaEditorComponent

tag="textarea"

/>

</div>

<div>

<button className='hover:shadow-form rounded-md bg-white border py-3 px-8 text-base font-semibold outline-none text-gray-700'>

Submit

</button>

</div>

</form>

);

Once you open the webpage, you’ll see the Froala WYSIWYG editor is on the form. You can use it to write and make your text look nice. But, when you send the form, the editor’s content isn’t checked or sent along with it.

Submit Froala editor content along with react-hook-form submitted data in NextJS app

To validate and submit the Froala editor content along with react-hook-form submitted data, we will use the react-hook-form’s `Controller` component. This component is useful for creating a field that updates its value based on an externally controlled component, such as the Froala React rich-text editor component

First, import the `Controller` component:

import { useForm, Controller } from 'react-hook-form';

Then, Add a new variable `control` which will be used with the `Controller` component.

const { register, handleSubmit, control, formState: { errors } } = useForm();

Finally, replace the message field and Froala Editor component code with the `Controller` component :

<div className='mb-5'>

        <label htmlFor='message' className='mb-3 block text-base font-medium text-black'>

Message

</label>

<Controller

name="message"

rules={{ required: true }}

control={control}

defaultValue=""

render={({ field }) => (

<FroalaEditorComponent

tag="textarea"

model={field.value}

onModelChange={field.onChange}

/> )}

/>

</div>

In the `Controller` component:

  • We used the `name` property to identify the data when the form is submitted. The `control` property is used to control the form.
  • We used the rules property to set the validation rules.
  • The `render` method is used to render the editor and connect it with the form. inside it:
    • we used the `field` argument to get the current value and the onChange event of the form field.
    • The `model` property is used to bind the current value to the Froala Editor.
    • The `onModelChange` event is used to update the form field value when the Froala Editor content changes.

This way, the Froala Editor is fully integrated with the form, and its content is validated and submitted along with the other form fields.

Now, when you open the app and submit the form, the content of the Froala Editor will be included in the form data. The error messages, if any, will be displayed in the console.

NextJs rich text form

Customize the editor

To customize the editor toolbar, you can pass an options object to the Froala Editor component. This object should contain the desired configuration options from the Froala API options. Here’s an example:

const options = {

toolbarButtons: [ 'bold', 'italic', 'underline', 'outdent', 'indent', 'undo', 'redo', 'clearFormatting', 'selectAll'  ],

charCounterMax: 140

}

You can then pass the options object to the Froala Editor component’s config property like so:

<FroalaEditorComponent

tag="textarea"

model={field.value}

onModelChange={field.onChange}

config={options}

/>

This will customize the toolbar to only include the specified buttons and set the maximum character count to 140 characters.

Note that some editor buttons and functions require additional plugins to be loaded. You have to import the plugin file

import 'froala-editor/js/plugins/align.min.js';

import 'froala-editor/js/plugins/char_counter.min.js';

Include it in the `pluginsEnabled` option, and add the buttons to be displayed in the `toolbarButtons` option:

const options = {

toolbarButtons: [ 'bold', 'italic', 'underline', 'alignRight', 'alignCenter',  'alignLeft', 'outdent', 'indent', 'undo', 'redo', 'clearFormatting', 'selectAll'  ],

pluginsEnabled: ['align', 'charCounter'],

charCounterMax: 140

}

custom Froala rich text editor in NextJS

Full Code

Here is the complete code of “contact.tsx” component with all the changes:

'use client';

import React from 'react';
import { useForm, Controller } from 'react-hook-form';

import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/css/froala_editor.pkgd.min.css';
import 'froala-editor/js/plugins/align.min.js';
import 'froala-editor/js/plugins/char_counter.min.js';

import FroalaEditorComponent from 'react-froala-wysiwyg';

export default function Contact() {
  const { register, handleSubmit, control, formState: { errors } } = useForm();
  const onSubmit = (data: any) => console.log(data);
  console.log(errors);

  const options = {
    toolbarButtons: [ 'bold', 'italic', 'underline', 'alignRight', 'alignCenter',  'alignLeft', 'outdent', 'indent', 'undo', 'redo', 'clearFormatting', 'selectAll'  ],  
    pluginsEnabled: ['align', 'charCounter'],
    charCounterMax: 140
  } 

return (
    <form
    className="w-full max-w-5xl"
    onSubmit={handleSubmit(onSubmit)}
    >
      <div className='mb-5'>
        <label
          htmlFor='name'
          className='mb-3 block text-base font-medium text-black'
        >
          Full Name
        </label>
        <input
          type='text'
          placeholder='Full Name'
          className='w-full rounded-md border border-gray-300 bg-white py-3 px-6 text-base font-medium text-gray-700 outline-none focus:border-purple-500 focus:shadow-md'
          {...register('name', { required: true })}
        />
      </div>
      <div className='mb-5'>
        <label
          htmlFor='email'
          className='mb-3 block text-base font-medium text-black'
        >
          Email Address
        </label>
        <input
          type='email'
          placeholder='[email protected]'
          className='w-full rounded-md border border-gray-300 bg-white py-3 px-6 text-base font-medium text-gray-700 outline-none focus:border-purple-500 focus:shadow-md'
          {...register('email', { required: true })}
        />
      </div>

      <div className='mb-5'>
        <label
          htmlFor='Mobile number'
          className='mb-3 block text-base font-medium text-black'
        >
          Mobile number
        </label>
      <input 
       type="tel"
       placeholder="Mobile number"
       className='w-full rounded-md border border-gray-300 bg-white py-3 px-6 text-base font-medium text-gray-700 outline-none focus:border-purple-500 focus:shadow-md'
        {...register("Mobile number", {required: true, minLength: 6, maxLength: 12})}

      />
      </div>

      <div className='mb-5'>
      <label
          htmlFor='message'
          className='mb-3 block text-base font-medium text-black'
        >
          Message
        </label>
      <Controller   name="message" rules={{ required: true }}  control={control}   defaultValue=""   render={({ field }) => ( 
            <FroalaEditorComponent 
                    tag="textarea"
                    model={field.value}
                    onModelChange={field.onChange}
                    config= {options}
             /> )}
        />
      </div>

      <div>
        <button className='hover:shadow-form rounded-md bg-white border py-3 px-8 text-base font-semibold outline-none text-gray-700'>
          Submit
        </button>
      </div>
    </form>
  );
}

Concluding Remarks

The Froala WYSIWYG editor provides a rich set of options for text manipulation, and its React component allows for easy integration with your React and NextJS applications. Using the `react-hook-form` library’s `Controller` component, we can seamlessly integrate the Froala editor into a form created using `react-hook-form`, ensuring its content is validated and submitted alongside other form data. With the configuration options provided by the Froala API, we can customize the editor to fit our application’s needs.

Whether you are building a blog, a CMS, or any other application that requires text editing, the Froala WYSIWYG editor is a powerful tool that can enhance your project’s functionality and user experience. Start your free trial now and enable your users to create and manage content in a visually appealing and intuitive way.

Customize the Froala Font Family Plugin in React App Project

Font Family Plugin

The choice of font family plays a significant role in the communication effectiveness of the content. Different font families can convey varying tones of a message.

Some key reasons to use different fonts are readability, clarity, hierarchy, branding, consistency, compatibility, and accessibility.

Froala is a WYSIWYG HTML editor that offers a range of plugins to enhance the editing experience. One plugin is the Froala Font Family Plugin, which allows users to change fonts in their text.

Here, we will walk you through the process of including the Froala Font Family Plugin, as in this example, in a React project, step by step with Froala’s react rich text editor.

Font Family Plugin

Step 1: Setting up your React Project

If you already have a React project, you can skip this step.

Otherwise, open your terminal and run the below commands:

npx create-react-app froala-font-family-demo

cd froala-font-family-demo

This will create a new React project called “froala-font-family-demo.”

Step 2: Install Froala Editor

You need to have the Froala Editor integrated into your React project.

npm install react-froala-wysiwyg --save

Step 3: Create the component

Once you have installed Froala Editor, you need to import the editor in Froala default mode into your React component.

You can use this code on the App.js file of the React App project.

import './App.css';

import FroalaEditorComponent from "react-froala-wysiwyg";

import "froala-editor/css/froala_style.min.css";

import "froala-editor/css/froala_editor.pkgd.min.css";

import "froala-editor/js/plugins.pkgd.min.js";

function App() {

let model = '<p><a href="https://froala.com">Froala WYSIWYG Editor</a></p>';

return (

<div id="froala-editor">

<h1>Froala</h1>

<FroalaEditorComponent

tag="textarea"

model={model}

config={{

}}

/>

</div>

);

}

export default App;

Let’s break down the code:

Import Statements:

  • import ‘./App.css’; – The line imports a CSS file named App.css.
  • import FroalaEditorComponent from “react-froala-wysiwyg”; – The line imports the Froala Editor react component from “react-froala-wysiwyg” library.
  • The following lines import CSS and JavaScript files of the Froala Editor.

function App() { … } – This code defines a function component named App. In React, function components are used to create UI elements.

model Variable – let model initialize a model variable with an HTML string, that represents the initial content that will be displayed.

JSX Structure – The return statement contains a JSX structure, which defines the rendered output. JSX is a syntax extension for JavaScript often used with React.

<div id=”froala-editor”> – This div element has an id of “froala-editor.” It serves as a container for the component.

<h1>Froala</h1> – This is an <h1> heading that displays the text “Froala.”

<FroalaEditorComponent> – The code is the core component from the “react-froala-wysiwyg” library, which embeds the editor in the app.

tag=”textarea” – This prop specifies that it should be rendered as a textarea element.

model={model} – This prop provides the initial content to be displayed in the editor.

config={{}} – This prop can be used to pass additional configuration options to the editor.

export default App; – This line exports the App component as the default export of this module. This makes it available for use in other parts of the application.

 

Step 4: Add & Customize the Froala Font Family Plugin

Now that you have set up the Froala Editor in your React component, the Froala Font Family Plugin is added by default as we have included the “froala-editor/js/plugins.pkgd.min.js” file which imports all Froala plugins, and we have kept the pluginsEnabled API option unchanged.

Now it’s time to add more font families to the editor using the Froala Font Family Plugin.

This can be done by including the fontFamily API option in the Froala editor component config. Specify the font families that will be available in the editor.

Here we are using Roboto, Oswald, Montserrat, and Open Sans.

return (

<div id="froala-editor">

<h1>Froala</h1>

<FroalaEditorComponent

tag="textarea"

model={model}

config={{

fontFamily: {

"Roboto,sans-serif": 'Roboto',

"Oswald,sans-serif": 'Oswald',

"Montserrat,sans-serif": 'Montserrat',

"'Open Sans Condensed',sans-serif": 'Open Sans Condensed'

},

fontFamilySelection: ['true']

}}

/>

</div>

);

The code is an extension of the previous code.

fontFamily – This configuration defines a mapping between font families and their display names. It allows users to select fonts for their text content within the editor. Roboto, Oswald, Montserrat and Open Sans.

fontFamilySelection – This option is set to [‘true’], which indicates that the font family selection feature is enabled.

add fonts using Font Family Plugin

Step 5: Including the CSS code of the fonts

You need to include the fonts that will be used in your application. These are CSS-type codes.

In this project, we will use four Google fonts: Roboto, Oswald, Montserrat, and Open Sans Condensed.

In the file index.html, which is on the project file, use the following code in the <head>:

<link href='https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic,700,700italic&subset=latin,vietnamese,latin-ext,cyrillic,cyrillic-ext,greek-ext,greek' rel='stylesheet' type='text/css'>

<link href='https://fonts.googleapis.com/css?family=Oswald:400,300,700&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>

<link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700&subset=latin,greek,greek-ext,vietnamese,cyrillic-ext,cyrillic,latin-ext' rel='stylesheet' type='text/css'>

The code is a set of HTML <link> elements that are used to include fonts in a page.

These fonts are hosted on the Google Fonts service, and the code specifies which fonts and font variations to include on the web page.

Let’s break down each of the <link> elements. The <link> for the “Roboto” font:

<link href='https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic,700,700italic&subset=latin,vietnamese,latin-ext,cyrillic,cyrillic-ext,greek-ext,greek' rel='stylesheet' type='text/css'>

The href attribute is the URL of the font stylesheet. The rel specifies that this is a stylesheet link. The type indicates the type as ‘text/css’.

In the URL, Roboto weights and styles included are 400 regular, 300 light, 300 italic, 400 italic, 700 bold, 700 italic.

&subset=latin,vietnamese,latin-ext,cyrillic,cyrillic-ext,greek-ext,greek specifies which character subsets to include.

The next element references the Google Fonts API for the “Oswald” font family. It specifies the weights 400, 300, and 700 for the font. It includes character subsets for Latin and Latin-extended characters.

<link href='https://fonts.googleapis.com/css?family=Oswald:400,300,700&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

The next <link> is for the “Montserrat” font family. It includes font weights 400 and 700.

<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>

The next element references the Google Fonts API for the “Open Sans Condensed” font family.

It specifies font weights 300, 300 italic, and 700. It includes multiple character subsets, such as Latin, Greek, Greek extended, Vietnamese, Cyrillic extended, Cyrillic, and Latin extended.

<link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700&subset=latin,greek,greek-ext,vietnamese,cyrillic-ext,cyrillic,latin-ext' rel='stylesheet' type='text/css'>

Font Family Plugin customized

Conclusion

Incorporating the Froala Font Family Plugin into your React project is a way to enhance rich text editing capabilities.

In this article, we have covered the step-by-step process of adding the Froala Font Family Plugin to your React application.

Froala Editor and its plugins offer a range of features and options, making it a versatile tool for web developers.

You can create a user-friendly text editing experience for your application’s users. In other words, you can continue to improve the functionality of a rich text editor in a React project.

User Experience with Bootstrap and Froala WYSIWYG Editor

Detailed aspects or features of Froala Editor, focusing on user experience and capabilities.

Bootstrap is a popular CSS framework that offers a variety of pre-designed components for building responsive, mobile-first web applications. Froala, on the other hand, is a powerful and flexible WYSIWYG editor that enhances the user experience by allowing them to create and edit rich text content directly on the web page.

When combined, these two tools can greatly enhance the functionality and user experience of your web forms. In this article, we will demonstrate this by creating a responsive form with Bootstrap and then integrating Froala to allow users to format their messages with different styles, fonts, and colors. This can make their queries more organized and clear, leading to better communication.

Start with a simple Bootstrap form

You can easily create a responsive HTML form using the Bootstrap form component. Moreover, there are many free ready-made Bootstrap form examples that we can copy their code. This is a good example. Let’s copy and modify it a little to make it consistent with your brand:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Bootstrap WYSIWYG Editor</title>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<style>




body{

background-color: #25274d;

}




.col-md-3{

background: #ff9b00;

border-top-left-radius: 0.5rem;

border-bottom-left-radius: 0.5rem;

}




.col-md-9{

background: #fff;

padding: 3%;

border-top-right-radius: 0.5rem;

border-bottom-right-radius: 0.5rem;

}




h1{

color:white;

width:100%;




}




</style>

</head>

<body>

<!------ Include the above in your HEAD tag ---------->




<div class="container py-5">

<div class="row">

<div class="col-md-12 pt-5 pb-3">

<h1 class="text-center">Please let us know how we can help you !</h1>

</div>

</div>

<div class="row">

<div class="col-md-3 pt-5">

<div>

<h2>Contact Us</h2>

<p>We would love to hear from you !</p>

</div>

</div>

<div class="col-md-9 ">

<div class="contact-form pt-2">

<div class="form-group">

<label class="control-label col-sm-2" for="fname">First Name:</label>

<div class="col-sm-10">

<input type="text" class="form-control" id="fname" placeholder="Enter First Name" name="fname">

</div>

</div>

<div class="form-group">

<label class="control-label col-sm-2" for="lname">Last Name:</label>

<div class="col-sm-10">

<input type="text" class="form-control" id="lname" placeholder="Enter Last Name" name="lname">

</div>

</div>

<div class="form-group">

<label class="control-label col-sm-2" for="email">Email:</label>

<div class="col-sm-10">

<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">

</div>

</div>

<div class="form-group">

<label class="control-label col-sm-2" for="comment">Comment:</label>

<div class="col-sm-10">

<textarea class="form-control" rows="5" id="comment"></textarea>

</div>

</div>

<div class="form-group">

<div class="col-sm-offset-2 col-sm-10">

<button type="submit" class="btn btn-primary">Submit</button>

</div>

</div>

</div>

</div>

</div>

</div>




</body>

</html>

In the above code, we have included the Bootstrap stylesheet in the head section

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

We created two columns and added the form inside the right column. The form contains fields for the user’s first name, last name, email, and a comment section.

<div class="container py-5">

<div class="row">

<div class="col-md-12 pt-5 pb-3">

<h1 class="text-center">Please let us know how we can help you !</h1>

</div>

</div>

<div class="row">

<div class="col-md-3 pt-5">

<div>

<h2>Contact Us</h2>

<p>We would love to hear from you !</p>

</div>

</div>

<div class="col-md-9 ">

<div class="contact-form pt-2">

<div class="form-group">

<label class="control-label col-sm-2" for="fname">First Name:</label>

<div class="col-sm-10">

<input type="text" class="form-control" id="fname" placeholder="Enter First Name" name="fname">

</div>

</div>

<div class="form-group">

<label class="control-label col-sm-2" for="lname">Last Name:</label>

<div class="col-sm-10">

<input type="text" class="form-control" id="lname" placeholder="Enter Last Name" name="lname">

</div>

</div>

<div class="form-group">

<label class="control-label col-sm-2" for="email">Email:</label>

<div class="col-sm-10">

<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">

</div>

</div>

<div class="form-group">

<label class="control-label col-sm-2" for="comment">Comment:</label>

<div class="col-sm-10">

<textarea class="form-control" rows="5" id="comment"></textarea>

</div>

</div>

<div class="form-group">

<div class="col-sm-offset-2 col-sm-10">

<button type="submit" class="btn btn-primary">Submit</button>

</div>

</div>

</div>

</div>

</div>

</div>

We used Bootstrap classes to style the form and make it responsive. The “container” class creates a container with a responsive fixed width, while the “row” and “col-md-*” classes create a flexible grid system.

For the page background and text colors, we added them using custom styles.

body{

background-color: #25274d;

}

.col-md-3{

background: #ff9b00;

border-top-left-radius: 0.5rem;

border-bottom-left-radius: 0.5rem;

}

.col-md-9{

background: #fff;

padding: 3%;

border-top-right-radius: 0.5rem;

border-bottom-right-radius: 0.5rem;

}

h1{

color:white;

width:100%;

}

Contact us Bootstrap form

Integrating Froala with the form

Now that we have a basic comment field where users can’t style their message. Let’s make it more dynamic by integrating the Froala rich text editor. This will allow users to send a rich text message which is much more engaging.

To incorporate Froala into your Bootstrap form, you first need to include the Froala stylesheets and scripts in our HTML file.

<link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />

<script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>

We used CDN links to load Froala. The term froala-editor@latest in the URL ensures that we always get the latest version of Froala.

The term froala_editor.pkgd.min.js in the URL will Load the editor and all its plugins. If you want to just load the core editor replace it with froala_editor.min.js

After that, you can initialize the Froala editor on the comments field or any other field in your form.

Since the comments field defined ID is “comment“, the Froala initializing function will be called like this:

<script>

new FroalaEditor('#comment');

</script>

Now, when you reload your page, you will see a rich text editor in place of the comment field.

bootstrap form with Froala WYSIWYG editor

Because it’s just a basic contact form, you don’t need to include all the advanced editor features. Use the toolbarButtons API option to display the needed buttons only.

<script>

new FroalaEditor('#comment', {

toolbarButtons: {

'moreText': {

'buttons': ['bold', 'italic', 'underline', 'strikeThrough'],

'buttonsVisible': 4

},

'moreParagraph': {

'buttons': ['alignLeft', 'alignCenter', 'alignRight', 'alignJustify'],

'buttonsVisible': 4

},

'moreRich': {

'buttons': ['formatOLSimple', 'formatUL',  'paragraphFormat', 'undo', 'redo', 'fullscreen', 'fontSize', 'textColor', 'backgroundColor','insertLink']

},

}

});

</script>

bootstrap WYSIWYG editor

You can also set the iframe API option to true so that the editor’s style is not affected by other page styles.

Explore other Froala API options and customize them to your needs.

Add focus to the Bootstrap form

 

bootstrap form with Froala WYSIWYG editor

Bootstrap form input elements are known for their box shadow effect that appears when they are focused. Initializing Froala on a Bootstrap form input will make the box shadow effect not work. Let’s put it back so that form inputs look consistent when focused. Change the initializing code to the following.

new FroalaEditor('#comment', {

toolbarButtons: {

'moreText': {

'buttons': ['bold', 'italic', 'underline', 'strikeThrough'],

'buttonsVisible': 4

},

'moreParagraph': {

'buttons': ['alignLeft', 'alignCenter', 'alignRight', 'alignJustify'],

'buttonsVisible': 4

},

'moreRich': {

'buttons': ['formatOLSimple', 'formatUL',  'paragraphFormat', 'undo', 'redo', 'fullscreen', 'fontSize', 'textColor', 'backgroundColor','insertLink']

},

},

events : {

initialized(){

this.$box[0].style.transition = "border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out";

},

focus(){

this.$box[0].style.boxShadow = "0 0 0 .2rem rgba(0, 123, 255, .25)";

},

blur(){

this.$box[0].style.boxShadow = "";

}

}

});

</script>

In the above code, we used the Froala focus and blur events to handle adding a box shadow around the editor when it is focused and removing it when it is not.

The `initialized()` function is called when the editor is first created. Here we add a CSS transition property to the Froala editor box. This will give a smooth transition when the box-shadow is added or removed.

The `focus()` function is called when the editor is focused. Here we add a box-shadow around the editor box. This will be the same as the Bootstrap input focus box-shadow.

The `blur()` function is called when the editor is unfocused. Here we remove the box-shadow.

Testing the Form

After integrating Froala with your form, it’s time to test it. Refresh your web page and try typing and formatting text in the comment section. If everything is set up correctly, your text should appear in the chosen format.

Displaying the contact form content

On the page you will display the data submitted through the contact form we created don’t forget to include the froala_style.min.css stylesheet

<link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_style.min.css' rel='stylesheet' type='text/css' />

and display the comment data inside an HTML element with the fr-view class.

<div class="fr-view">

Here comes the HTML edited with the Froala rich text editor.

</div>

These steps are required to preserve the look of the edited HTML outside of the rich text editor.

Insert Images or files in the comments field

In case you want to enable your users to insert images or files into the comments field, Froala also provides an easy way to do so. Besides, you need to include the additional buttons for file and image upload in the toolbarButtons option, you will need to handle uploading the images or files into your server.

For specific instructions on how to perform each of these tasks with the Froala editor in the most popular server-side languages, check out our detailed guides.

The Froala editor also has documentation on a multitude of server-side SDKs in many languages to ease your development process.

Take Your Bootstrap Forms to the Next Level with Froala Rich Text Content Editor

The Froala Rich Text Content Editor is a powerful tool that can be seamlessly integrated into your Bootstrap forms. It provides an intuitive WYSIWYG interface, offering a plethora of features such as text formatting, image upload, and embedding options. With Froala, you can create rich, engaging form inputs that go beyond simple text fields. From bullet lists to embedded videos, the possibilities are endless. Plus, it’s highly customizable, allowing you to tailor the editor to your specific needs. Start enriching your forms today with Froala.

How to Use the Froala Markdown Plugin: Item-by-Item

Froala Markdown Plugin

Markdown is a lightweight markup language used for formatting and structuring plain text. It provides a way to create rich text content, such as headings, bold text, italics, code blocks, and lists without the need for complex HTML.

Markdown was born in the early 2000s, drawing inspiration from markup languages that had surfaced a decade earlier. These markup languages were initially used for emails and web posts during the early days of the Internet’s rise to popularity.

Markdown is especially popular in web development, documentation, and content creation.

Froala Markdown Plugin serves as a powerful tool, enabling seamless integration of Markdown capabilities into your web applications. This provides a user-friendly and efficient method for formatting content.

In this guide, we will explore how to use the Froala Markdown Plugin and provide detailed examples of Markdown features. We will cover the following Markdown elements:

  • Headings
  • Bold Text
  • Italic Text
  • Blockquotes
  • Ordered Lists
  • Unordered Lists
  • Code
  • Fenced Code Blocks
  • Horizontal Rules
  • Links
  • Images
  • Tables
  • Footnotes
  • Strikethrough
  • Task Lists

Markdown editor

Markdown button

In Froala, the Markdown button is the default on the toolbar. But you can customize the buttons on the toolbar and to include this option you must use the following code.

toolbarButtons: [...,'markdown',...]

Markdown button

Headings

Markdown headings are created using hashtags (#). Headings are essential for structuring your document and making it more readable. They allow you to create sections. Markdown provides an intuitive way to define headings using the hashtag symbol (#).

There are multiple levels of headings, and the number of symbols determines the heading level.

# Heading 1

## Heading 2

Heading 3

Markdown Heading

Bold and Italic Text

Markdown provides a straightforward way to format text as bold and italic.

These formatting styles are commonly used for emphasizing text in documents.

To make text bold in Markdown, you can enclose the text in double asterisks (**):

This is **bold** text.

Italicized text is created by enclosing the text in single asterisks (*):

This is *italic* text.

Markdown bold text

Blockquotes

Blockquotes in Markdown allow you to visually set apart and emphasize text, making it clear that the content is a quotation or excerpt from another source. They help improve the readability and structure of t documents.

Markdown uses the greater-than sign (>) to create blockquotes.

> This is a blockquote.

Markdown Blockquotes

Ordered and Unordered Lists

Ordered lists are created using numbers followed by periods. Each list item should start with a number, and Markdown will take care of numbering automatically:

  1. Item 1
  2. Item 2
  3. Item 3

Unordered lists are created using asterisks (*), plus signs (+), or hyphens (-) as list markers. Markdown will format them as bullet points:

* Item 1

* Item 2

* Item 3

Markdown list

Inline Code and Fenced Code Blocks

In Markdown, you can easily include code snippets and code blocks using backticks (`) and fenced code blocks. These features are useful for documenting code and sharing programming examples.

To format text as inline code, enclose the code within backticks (`).

Inline code is typically used for short code snippets or referencing code elements within sentences or paragraphs.

This is `inline code`.

Fenced code blocks are used to display longer code snippets, complete code examples, or multiline code.

They are enclosed by triple backticks ( “`), and you can specify the programming language for syntax highlighting immediately after the opening backticks.

“`

// This is a fenced code block

function example() {

console.log(‘Hello, World!’);

}

“`

Markdown code block

Horizontal Rules

Horizontal rules, also known as horizontal lines or thematic breaks, are used in Markdown to separate content visually.

They are an effective way to create visual divisions within your text. Horizontal rules are often used to denote changes in topics, sections, or content breaks.

To create a horizontal rule in Markdown, use three or more hyphens (—), asterisks (***), or underscores (___) on a separate line:

Links and Images

In Markdown, you can create hyperlinks and embed images in your text using an intuitive syntax. This makes it easy to add links to external websites, and internal resources, and include images within your Markdown documents.

To create hyperlinks in Markdown, you typically use the following format:

Link Text: This is the text that will be displayed as a clickable link.

URL: This is the web address or destination to which the link points.

Markdown allows you to create hyperlinks by enclosing the link text in square brackets ([]) and the URL in parentheses (()):

[Froala](https://froala.com)

Markdown allows you to embed images within your documents using a similar syntax to links. The primary difference is that you precede the URL with an exclamation mark (!).

Alt Text: This is a description of the image. It’s used for accessibility and is displayed when the image cannot be loaded.

Image URL: This is the web address of the image you want to embed.

![Froala Logo](https://froala.com/wp-content/uploads/2022/06/froala-1.png )

Markdown image element

Tables

In Markdown, you can create tables to present data in a structured and organized format. Markdown tables are easy to create and offer a simple way to display information with columns and rows.

To create tables in Markdown, you use a combination of pipe characters (|) and hyphens (-) to define the structure of the table and pipe characters for the content within each cell.

| Header 1 | Header 2 |

|———-|———-|

| Data 1   | Data 2   |

| Data 3   | Data 4   |

The first row defines the table headers, which are separated by the pipe character (|) and enclosed with pipes on both sides.

The second row, consisting of hyphens (-), indicates the alignment and separates the header row from the content rows.

Subsequent rows contain the data cells, which are separated by pipe characters.

Markdown tables

Footnotes

Footnotes in Markdown provide a way to add additional information or references to your content without cluttering the main text.

Create the reference point in your main text: To indicate where you want to add a footnote, place a caret (^) or a superscript number in your text. For example, you might write something like this:

This is a sentence with a footnote reference[^1].

Add the footnote content: At the bottom of your document or section, create a separate section to define the footnotes. This is done by placing the caret or number again followed by a colon and then the content of the footnote.

[^1]: This is the content of the footnote. It can be multiple sentences or even paragraphs.

markdown footernotes

Strikethrough

Strikethrough in Markdown is a way to visually indicate that text should be crossed out or deleted. This is typically used to show that a word or phrase has been removed or is no longer valid.

To apply strikethrough formatting in Markdown, use double tilde (~~) characters. Here’s how it works:

This is some ~~strikethrough text~~.

Markdown strikethrough

Task Lists

Task lists are used to create to-do lists with checkboxes.

To create a task list in Markdown, use square brackets ([]) to represent incomplete tasks and [x] to represent completed tasks:

– [x] Task 1

– [ ] Task 2

– [ ] Task 3

Markdown task lists

Conclusion

The Froala Markdown Plugin is a versatile tool for integrating Markdown support into your web applications.

It allows you to easily create and render Markdown content, making it a valuable addition to your text editing solutions.

In this guide, we’ve covered the basics of using the Froala Markdown Plugin and provided examples for various Markdown features.

Whether you’re building, the Markdown Plugin can streamline the process and enhance the user experience.

With customization options, you can ensure that Markdown content seamlessly integrates with your website’s design.

So, go ahead and explore the possibilities of the Froala Markdown Plugin in your projects. Happy editing!

How to customize Froala Image Edit Buttons in a React App

The Froala Editor lets users create and edit content with rich text formatting. One of its powerful features is the ability to work with images.

This article explains how to use Image Edit Buttons from Froala Editor in a React app project with a cheap react rich text editor.

Prerequisites

Before you get started, make sure you have the following prerequisites in place:

  • Node.js and npm are installed on your computer.
  • A React application set up.
  • Knowledge of React and HTML.
  • Setting up Froala Editor in a React App

First, we need to install the required packages. After that, we can initialize the Froala Editor.

We will make a React component called App.js. In this component, we will set up and use the Froala Editor along with the Image Edit Buttons.

1. Installation and Setup

First, install the required packages. You can do this by running the following command in your React project directory:

npm install react-froala-wysiwyg

cd react-froala-wysiwyg

npm install react-froala-wysiwyg --save

These commands install the Froala Editor and its React wrapper.

2. Importing Dependencies

In your App.js file, import the necessary dependencies.

Here’s the beginning of the file with the imports:

import { useState } from "react";

import "froala-editor/css/froala_style.min.css";

import "froala-editor/css/froala_editor.pkgd.min.css";

import "froala-editor/js/plugins.pkgd.min.js";

import FroalaEditorImg from "react-froala-wysiwyg/FroalaEditorImg";


We imported useState from React to manage the component state in the code above.

We imported the react-froala-wysiwyg package’s styles, plugins, and components.

 

3. Setting Up the Component

Next, create the App component and set up the basic structure.

We’ll use the FroalaEditorImg component to render the Froala Editor. Here’s the code for the App component:

export default function App() {

  const [state, setState] = useState({

    src: "https://fakeimg.pl/350x200/?text=Click to test"

  });




  const handleModelChange = (model) => {

    setState({

      content: model

    });

  };




  const config = {

    imageEditButtons: [

      "imageReplace",

      "imageAlign",

      "imageCaption",

      "imageRemove",

      "|",

      "imageLink",

      "linkOpen",

      "linkEdit",

      "linkRemove",

      "-",

      "imageDisplay",

      "imageStyle",

      "imageAlt",

      "imageSize"

    ]

  };




  return (

    <div>

      <FroalaEditorImg

        config={config}

        model={state}

        onModelChange={handleModelChange}

      />

      <br /> <br />

    </div>

  );

}


Now, let’s break down the code step by step:

We start by defining the App component as a functional component.

Inside the component, we use the useState hook to manage the state.

The state object holds the initial image source, displayed in the editor.

export default function App() {

  const [state, setState] = useState({

    src: "https://fakeimg.pl/350x200/?text=Click to test"

  });

We define the handleModelChange function, which will be called when the editor content changes. In this function, we update the state with the new content.

  const handleModelChange = (model) => {

    setState({

      content: model

    });

  };

The config object holds the Froala Editor’s configuration, including the imageEditButtons property.

This property specifies the set of image editing buttons you want to display.

  const config = {

    imageEditButtons: [

      "imageReplace",

      "imageAlign",

      "imageCaption",

      "imageRemove",

      "|",

      "imageLink",

      "linkOpen",

      "linkEdit",

      "linkRemove",

      "-",

      "imageDisplay",

      "imageStyle",

      "imageAlt",

      "imageSize"

    ]

  };

Finally, we build the FroalaEditorImg element, passing as props the config, model, and onModelChange.

This component will display the Froala Editor with the specified image edit buttons.

  return (

    <div>

      <FroalaEditorImg

        config={config}

        model={state}

        onModelChange={handleModelChange}

      />

      <br /> <br />

    </div>

  );

}

Explaining the imageEditButtons Configuration

The imageEditButtons configuration is a crucial part of this implementation. It defines the set of buttons that will appear when you click on an image in the Froala Editor.

Let’s break down the buttons included in the configuration:

“imageReplace”: This button allows you to replace the selected image with a new one.

“imageAlign”: It enables you to set the alignment of the image (left, center, right, or justify).

“imageCaption”: This button adds a caption to the image.

“imageRemove”: It lets you remove the selected image.

“|”: The pipe character (|) is used to create a separator between groups of buttons.

“imageLink”: You can link the image to another URL.

“linkOpen”: This button opens the link in a new window or tab.

“linkEdit”: It allows you to edit the image’s link.

“linkRemove”: This button removes the link from the image.

“-“: The hyphen character (-) is used to create a separator between groups of buttons.

“imageDisplay”: It controls the display settings for the image, such as size and alignment.

“imageStyle”: You can apply custom styles to the image.

“imageAlt”: This button adds an alternative text (alt text) to the image, which is essential for accessibility.

“imageSize”: It allows you to adjust the dimensions of the image.

These buttons give users a variety of options for customizing and modifying photos within the Froala Editor.

Using the Froala Editor with Image Edit Buttons

Now that we’ve configured the Froala Editor with the desired image edit buttons, let’s discuss how to use the editor in your React app.

The FroalaEditorImg component is used to render the editor. Here’s how we set it up:

<FroalaEditorImg

  config={config}

  model={state}

  onModelChange={handleModelChange}

/>


We pass the config object as a prop, which contains our button configuration.

The model prop is set to state, allowing the editor to manage its content based on the state defined in the component.

The onModelChange prop is set to the handleModelChange function, which updates the state with the new editor content.

With this setup, the Froala Editor will be displayed with the specified image edit buttons, and you can interact with the image in various ways, as defined by the imageEditButtons configuration.

Testing the Implementation

To see the Image Edit Buttons in action, run your React app.

Make sure to start your development server using the following command:

npm start

This command will start your development server, and you should be able to access your React app in a web browser.

In your app, you’ll see the Froala Editor with the initial image and the configured Image Edit Buttons.

When you click on the image, the Image Edit Buttons will show up, allowing you to change the image, add a caption, align the image, and more.

As you make changes, the editor’s content will be updated, and you can observe this change in the handleModelChange function.

Froala image edit buttons

Conclusion

In this article, we have explained how to install Image Edit Buttons in a Froala Editor within a React app.

First, we set up the necessary dependencies.

Then, we configured the imageEditButtons property. We ended up using the FroalaEditorImg component.

It displays the editor and image editing options.

The imageEditButtons configuration has many image editing and customization features.

It is a powerful tool for working with images in your application.

By following the steps in this article, you can improve the user experience of your React app. Users will be able to edit and customize images.

You can also customize the image edit buttons to fit your needs.

Froala Editor User Experience Tips – part 2

froala tips and tricks

Froala WYSIWYG editor has a powerful API with over 240 API options, 100+ events, and 220+ methods. In the “Froala’s tips and tricks – part 1” article, We started to explain how to use the Froala editor API to maximize and enhance the user experience, usage, and productivity. We are excited to continue on this journey by uncovering more valuable tips and tricks of the Froala editor.

Highlighting and Beautifying HTML Code for a Seamless User Experience

WYSIWYG editors were invented to allow users to create rich-text content without needing to know HTML. However, for tech-savvy users or developers, Froala provides a built-in feature to write and edit the content HTML code.

When dealing with large amounts of content within the editor, modifying the HTML code can become quite challenging, even for experienced developers, unless it is properly highlighted and beautified.

To address this issue, Froala has developed the CodeBeautifier plugin, which helps in arranging the code in a more readable format. With the help of this plugin, users can easily comprehend and modify the structure of the HTML code.

Furthermore, it is easy to integrate Froala with codeMirror which highlights the code making the editing process quite handy for developers.

To integrate codeMirror with Froala, simply ensure that the necessary CodeMirror stylesheet and script files are included within your webpage before calling the Froala scripts.

  • Make sure to configure the following API options correctly:

Display Shortcut Commands Hints in the Froala Editor

Another user-friendly feature of the Froala editor is the ability to use shortcuts for quick and easy to perform many editor commands. For example, you can use the (Ctrl+B or ⌘ Cmd + B) shortcut to bold the selected text in the editor. Using shortcuts is a real time-saver and efficiency booster for your users who are familiar with these shortcuts.

Users may not know these shortcuts are available and they can use them. To help them, you can display the shortcut code in the button tooltip by setting the shortcutsHint API option to true.

new FroalaEditor('.selector', { shortcutsHint: true });

Now, when the user hovers over any toolbar options, they will see a tooltip with the corresponding keyboard shortcut, providing a quick reference for users who prefer to use the keyboard over the mouse.

However, users can see the full list of available shortcuts by clicking on the editor help button, displaying the shortcodes in the tooltip can be an effective way to educate users about these productivity features.

Control Froala Editor with External Buttons

When it comes to developing your app, you may encounter situations where you need to have control over certain editor actions through an external button. No problem, with Froala you can do this easily. Before invoking the external button function, you need to ensure that the editor is correctly loaded and retrieve the editor instance to access its methods. This can easily done inside the initialized API event.

Let’s say you want to clear the editor’s content using an external button. To achieve this, you’ll need to add a click event listener inside the editor-initialized event. This way, when the user clicks on the clear button, the event will be triggered and you can use Froala API’s html.set method to clear the editor content. This method allows you to set the editor’s content in HTML format. In our case, we want to clear the content, so we’ll call the method with an empty argument. Here’s an example:

const editorInstance = new FroalaEditor('#edit', {

  events: {

    initialized: function () {

      const editor = this

      document.getElementById('clearButton').addEventListener("click", function () {

         editor.html.set('')

        editor. events.focus()

      })

    }

  }

})

In the above example, by clicking on the button with ID ‘clearButton’, the editor content will be cleared and the editor will be focused, ready to accept new input from users.

You can perform different actions by utilizing different Froala API methods to manipulate the editor’s behavior.

These sorts of interactions may allow an enhanced, user-friendly navigation and editing experience.

Control Multiple Editors Using A Shared Toolbar

Yet another brilliant feature of the Froala Editor is the ability to use one toolbar to perform actions in multiple editor instances on the same page. This can be extremely useful in cases where you have different editable sections but want to have centralized control over them using one toolbar. This shared toolbar can be positioned anywhere on the webpage and works in sync with the active editor instance.

To set up a shared toolbar, you need to set the toolbarContainer API option to the CSS selector of the element you want to use as your toolbar. Here’s an example:

new FroalaEditor("#edit1, #edit, #edit2", {

   toolbarContainer: '#foo',

    toolbarButtons: [ ['bold', 'italic', 'underline', 'strikeThrough', 'textColor', 'backgroundColor', 'emoticons'], ['paragraphFormat', 'align', 'formatOL', 'formatUL', 'indent', 'outdent'], ['insertImage', 'insertLink', 'insertFile', 'insertVideo', 'undo', 'redo'] ]

})

In the above example, we created three different editors on the following elements `#edit1`, `#edit`, and `#edit2` on the page. The shared toolbar of the three editors is placed inside the `#foo` HTML element.

By using this shared toolbar, users will only need to familiarize themselves with one toolbar to manage multiple editors, simplifying their editing experience and promoting efficiency.

Remember as we discussed in a previous article, when you are using multiple instances of the Froala editor on the same page, it is better to set the initOnClick option to true to lazy load the editors and improve the page performance.

Make Your Froala Editor Toolbar Sticky for Easy Navigation

The toolbar is an important element in WYSIWYG editors. It is the element where buttons are available to allow users to interact with the content. In a case where you have a lot of content in the editor, the toolbar might disappear as users scroll down the page, leading to a less efficient and user-friendly experience.

To address this, Froala offers the stickyToolbar API option. When set to true, the toolbar will move as users scroll in the editor box. Here’s an example of how you can activate this feature:

new FroalaEditor('div#froala-editor', {

toolbarSticky: true

})

Boosting User Experience with Advanced Features and Customization Options

In this article, we have discussed various features of the Froala WYSIWYG editor that enhance the user’s editing experience. We have covered respective aspects like displaying shortcut hints, using external buttons to perform actions, controlling multiple editors with a shared toolbar, and finally, incorporating a scrollable toolbar for easy and efficient navigation. Using these features, developers can ensure their applications provide a user-friendly and efficient editing experience to their end-users.

Remember, the power of the Froala editor is not confined to these features alone. Froala offers a multitude of APIs and options that developers can utilize to tailor the editor’s behavior to the specific needs of their applications. Explore the Froala documentation now, try it for free, and when you are ready, pick a plan that suits your project needs to leverage the full capabilities of this powerful editing tool without the unlicensed banner.

Happy coding!

Creating React Rich Text Editor for Right-to-Left Languages

RTL rich text React editor

Web apps must be ready for diverse audiences in a globalized world, including those who read and write in RTL languages such as Arabic, Hebrew, and Persian.

Languages that are written and read from right to left are called RTL languages.

In contrast to left-to-right languages like English, where text flows from left to right, RTL languages follow a reversed direction.

This means that the first letter in a word is on the right side of the page. The other letters go to the left.

When a sentence starts, it begins on the right side and progresses to the left.

One phase example in Arabic:

هذا مثال على الجملة العربية.

This is an example of an Arabic sentence.

In any media written in RTL languages, text alignment, and layout are reversed compared to LTR languages.

The right margin is considered the “starting” point, and the text is aligned right-justified.

Numerical values are typically written with the most significant digit on the right.

React editor for RTL language

Introduction to Froala Editor

Froala Editor is a popular WYSIWYG (What You See Is What You Get) editor that allows users to create and edit rich content in a user-friendly way.

In this project, we will integrate the Froala Editor into a React application, a great way to empower users to create and format text and images with our react rich text editor.

For RTL languages, some additional configurations are needed.

Step 1: Set Up Your React Project

If you haven’t already, create a new React project using create-react-app:

npx create-react-app froala-rtl-editor

cd froala-rtl-editor

Step 2: Install Froala Editor

Next, install Froala Editor by running the following commands:

npm install react-froala-wysiwyg --save

Step 3: Configuration Froala Editor

Once installed, open the App.js file and now, you can import the Froala Editor styles and the React component:

import React from 'react'; 

import FroalaEditorComponent from 'react-froala-wysiwyg'; 

import 'froala-editor/css/froala_style.min.css'; 

import 'froala-editor/css/froala_editor.pkgd.min.css';

Now, you can use the FroalaEditorComponent in your React component’s method:

 

 

With this integration, you can have a basic Froala Editor running in your React application.

Step 4: Configuration RTF

The official Froala Editor documentation provides a comprehensive guide on how to configure the editor for RTL languages.

According to the documentation, you should set the direction property in the configuration object to ‘rtl’ to enable RTL mode:

  <FroalaEditorComponent

        tag="textarea"

        model={model}

        config={{

          direction: 'rtl'

        }}

      />

    </div>

Running the Application

With the configuration and components in place, you can now start your React application:

npm start

Open your browser and navigate to http://localhost:3000 to see the Froala Editor integrated into your React app with RTL support.

RTL rich text react editor

Conclusion

This tutorial shows how to make a Froala Editor in a React app that supports right-to-left (RTL) languages.

Froala Editor is a strong tool for adding text editing features to your app. It can also be set up to work with RTL text, reaching more people.

Remember to customize the editor’s configuration to suit your specific project needs. Follow these steps to make your React application more accessible for RTL language users.

Gaining Comprehensive Control over Rich Text Editing with Froala React SDK Components

Froala React sdk components

Froala 4.1 brings support for the LTS version of React V18. With Froala 4.1 React SDK, integrating Froala into your React app is straightforward. The React SDK provides several components to enable rich-text editing capabilities as well as editing images, links, buttons, and inputs. In this article, we will explore the various components offered by the Froala React SDK and provide a comprehensive guide on how to effectively utilize them.

Intro

Before using any of the React SDK components, it is crucial to familiarize yourself with the Froala React integration process. Let me provide you with a quick overview of the essential steps that need to be followed before using the Froala React components.

  1. Install the Froala React SDK using
npm install react-froala-wysiwyg --save
  1.  Import the editor CSS stylesheets and the required plugin scripts
// Import the Froala Editor Stylesheet for displaying content outside the editor
import 'froala-editor/css/froala_style.min.css';


// Import the Froala Editor Stylesheet
import 'froala-editor/css/froala_editor.pkgd.min.css';


// Import all Froala Editor plugins;
import 'froala-editor/js/plugins.pkgd.min.js';

Froala React SDK components

Now we will be able to import and use the editor components.

Rich Text Editor Component

The text editor component is the cornerstone of Froala’s rich text editing capabilities. You can use it when you want to initialize the Froala WYSIWYG editor in your React app. Whether you want to use the full-featured WYSIWYG editor or make a customized version of it, this component is highly adaptable and configurable. It provides a host of options that allow you to custom-tailor the editor’s features to your specific use case. You can add or remove toolbar buttons, change the theme, or even set rules for HTML tag usage.

  1. Import the component
import FroalaEditorComponent from 'react-froala-wysiwyg';
  1.  Use it in your template where you want to display the editor
<FroalaEditorComponent

tag='textarea'

config={config}

model={model}

onModelChange={handleModelChange}

/>

The component has the following properties:

  • tag: used to tell on which tag the editor is initialized
  • config: used to customize the editor API options and events
  • model: used to hold the current value of the editor
  • onModelChange: a function triggered each time the value changes

Display Editor Content Component

Froala provides you with a component to display content created with the Froala editor

<FroalaEditor

model={content}

onModelChange={handleModelChange}

/>

Image Editor Component

The Image Editor component is another useful feature used to initialize the Froala editor on an image to enable image editing capabilities for your app. The users can replace and edit images directly in their content. The Image Editor supports various editing operations such as resizing, aligning, adding an image caption, adding an ALT keyword, and changing the image display property.

  1. Import the component
import FroalaEditorImg from "react-froala-wysiwyg/FroalaEditorImg";
  1. Use it in your template where you want to display the image editor
<FroalaEditorImg

config={config}

model={model}

onModelChange={handleModelChange}

/>

The component has the following properties:

  • config: used to customize the editor API options and events.

For image, button, input, and link components you can use reactIgnoreAttrs special API option to define the attributes that you want to ignore when the editor updates the froalaModel

config: {

reactIgnoreAttrs: ['class', 'id']

},
  • model: The model must be an object containing the attributes for your img tag
model={{

src: 'path/to/image.jpg',

width:"300px",

alt:"Old Clock"

}}
  • onModelChange: a function triggered each time the value changes

You can use the Image Editor Component to implement a free image uploader in your React app.

Full Image Editor Component Example:

import "./styles.css";

// Import the Froala Editor Stylesheet for displaying content outside the editor
import "froala-editor/css/froala_style.min.css";

// Import the Froala Editor Stylesheet
import "froala-editor/css/froala_editor.pkgd.min.css";

// Import all Froala Editor plugins;
import "froala-editor/js/plugins.pkgd.min.js";

import FroalaEditorImg from "react-froala-wysiwyg/FroalaEditorImg";

import { useState } from "react";

export default function App() {

const [state, setState] = useState({

src: "https://fakeimg.pl/350x200/?text=Click%20on%20me",

id: "froalaEditor",

tmpattr: "This attribute will be ignored on change."

});

const handleModelChange = (model) => {

setState({

content: model

});

};

const config = {

reactIgnoreAttrs: ["tmpattr"],

imageEditButtons: [

"imageReplace",

"imageAlign",

"imageCaption",

"imageRemove",

"|",

"imageLink",

"linkOpen",

"linkEdit",

"linkRemove",

"-",

"imageDisplay",

"imageStyle",

"imageAlt",

"imageSize"

]

};

return (

<div className="App">

<FroalaEditorImg

config={config}

model={state}

onModelChange={handleModelChange}

/>

<br /> <br />

<div> For More Info. Visit: https://froala.com/image-uploader/ </div>

</div>

);

}

Button Editor Component

The Button Editor component is a specialized component provided by Froala React SDK. It allows you to initialize the Froala editor on a button, offering custom button editing options.

  1. Import the component
import FroalaEditorButton from "react-froala-wysiwyg/FroalaEditorButton";
  1. Use it in your template where you want to display the button editor
<FroalaEditorButton

config={config}

model={model}

onModelChange={handleModelChange}

/>

The component has the following properties:

  • config: This is used to customize the editor API options and events
  • model: The model must be an object containing the attributes for your button tag. You can specify the button text using a special attribute named innerHTML which inserts the inner HTML of the element
model={{innerHTML: 'Click Me'}}
  • onModelChange: This is a function triggered each time the value changes

Full Button Editor Component Example:

import "./styles.css";

// Import the Froala Editor Stylesheet for displaying content outside the editor
import "froala-editor/css/froala_style.min.css";

// Import the Froala Editor Stylesheet
import "froala-editor/css/froala_editor.pkgd.min.css";

// Import all Froala Editor plugins;
import "froala-editor/js/plugins.pkgd.min.js";

import FroalaEditorButton from "react-froala-wysiwyg/FroalaEditorButton";

import { useState } from "react";

export default function App() {

const [state, setState] = useState({

innerHTML: "Click Me",

id: "myButton",

style: "color:red; padding:20px"

});

const handleModelChange = (model) => {

setState({

content: model

});

};

return (

<div className="App">

<FroalaEditorButton model={state} onModelChange={handleModelChange} />

</div>

);

}

Link Editor Component

The Link Editor component is another important part of the Froala React SDK, allowing the initialization of the Froala editor on hyperlink elements. With this, you can edit, remove, and style hyperlinks in your application content. The editor provides a range of options for hyperlink customization including URL entry, target attribute setting, and CSS class addition.

  1. Import the component
import FroalaEditorA from 'react-froala-wysiwyg/FroalaEditorA';
  1. Use it in your template where you want to display the link editor
<FroalaEditorA

config={config}

model={model}

onModelChange={handleModelChange}

/>

The component has the following properties:

  • config: This is used to customize the editor API options and events
  • model: The model must be an object containing the attributes for the hyperlink element. This could include the link URL, target attribute, and any CSS classes.
model={{

href: 'https://www.froala.com/',

target: '_blank',

}}
  • onModelChange: This is a function triggered each time the value changes

Full Link Editor Component Example:

import "./styles.css";

// Import the Froala Editor Stylesheet for displaying content outside the editor

import "froala-editor/css/froala_style.min.css";
// Import the Froala Editor Stylesheet

import "froala-editor/css/froala_editor.pkgd.min.css";

// Import all Froala Editor plugins;

import "froala-editor/js/plugins.pkgd.min.js";

import FroalaEditorA from "react-froala-wysiwyg/FroalaEditorA";

import { useState } from "react";

export default function App() {

const [state, setState] = useState({

innerHTML: "Click Me",

href: "https://www.froala.com/",

target: "_blank"

});

const config = {

linkEditButtons: ["linkOpen", "linkStyle", "linkEdit", "linkRemove"]

};

const handleModelChange = (model) => {

setState({

content: model

});

};

return (

<div className="App">

<FroalaEditorA

config={config}

model={state}

onModelChange={handleModelChange}

/>

</div>

);

}

Input Editor Component

The Input Editor component allows you to initialize the Froala editor on an input element of your React app, enabling customization of input fields. This is convenient when you want to provide users with a rich text input field instead of plain text.

  1. Import the component
import FroalaEditorInput from 'react-froala-wysiwyg/FroalaEditorInput';
  1. Use it in your template where you want to display the input editor
<FroalaEditorInput

config={config}

model={model}

onModelChange={handleModelChange}

/>

The component has the following properties:

  • config: This is used to customize the editor API options and events
  • model: The model must be an object containing the attributes of the input element.
model: {

placeholder: 'I am an input!'

}
  • onModelChange: This is a function triggered each time the value changes

Enhance Your React App with Powerful and Customizable Rich Text Editing Components

By using the Froala Editor React.js SDK, you gain a powerful set of tools to modify and enhance your app’s content, all with a high degree of customization. Whether you need to edit text, images, buttons, links, or inputs, Froala provides an effortless way to do so. With these components at your disposal, your React application can offer an enhanced user experience.

With its powerful and adaptable components, you will not only get an advanced WYSIWYG editor but also the ability to create an image uploader tool or a modern drag-and-drop webpage builder tool. Start your free trial now and experience the flexibility of Froala Editor SDK for React.js. Whether you’re building a blog, an e-commerce website, or any other web application that requires rich content editing, Froala Editor SDK for React.js is a tool worth considering.

Ultimate Guide to Migrating from TinyMCE to Froala in React

migrating from TinyMCE to Froala in React

In the latest release of Froala, version 4.1, we made a significant update by supporting the LTS React version among several other popular JavaScript frameworks. With this major update, we expect a considerable migration from TinyMCE to Froala. Whether you’re already a fan of Froala or currently facing challenges with TinyMCE and are considering a switch to Froala for your React app, this article aims to provide you with a smooth and efficient transition process. Throughout this guide, we will walk you through every step, ensuring a seamless migration from TinyMCE to Froala React SDK. From removing the TinyMCE component to installing and configuring the powerful Froala rich text editor React component, our goal is to equip you with the knowledge and confidence to make the switch.

 Why do users migrate from TinyMCE to Froala?

There are several reasons for users to migrate from TinyMCE to Froala, such as:

  1. Technology:
    Froala editor has its own unique way of handling content, leading to distinct and cleaner HTML outputs. Additionally, the Froala editor boasts different API structures. It introduces a developer-friendly API where its options, events, and methods are comprehensive and easy to use. This API enables effortless customization of the editor’s functionality and allows for the creation of custom elements and plugins, empowering developers with endless possibilities.
  2. Transparent Pricing:
    Froala distinguishes itself with a transparent pricing model that guarantees no hidden fees. Moreover, in all plans, all of Froala’s plugins are included, and there are no restrictions on editor usage. In contrast, TinyMCE’s pricing plans come with limitations on the number of page loads. For instance, the free plan only allows for 1000-page loads. For example, a company with 10 users each loading a page containing the TinyMCE editor 10 times per day, would exhaust the capacity in just 10 days, forcing them to pay $40 for an additional 1000 loads. This would result in a monthly expense of $80, or a whopping $960 annually. Remarkably, the cost of Froala’s professional plan is actually lower than this. What’s more, the free Tinymce plan is limited to a single domain, lacks access to all plugins, and does not provide professional support.
  3. Multiple React components:
    In contrast to Tinymce, Froala React SDK stands out for its versatility, offering not just one but multiple React components. These components include a main component for rendering the editor, a component to preview the editor’s content, and some special components for initializing the editor on the <img>, <button>, <input>, and <a> HTML elements. With Froala React SDK, you’re equipped with a powerful toolkit to enhance both the functionality and presentation of your content.
  4. Design:
    The Froala UI has gained immense popularity among users for its sleek and captivating design. From its modern flat layout to captivating SVG icons, Froala Editor truly stands apart from other options available. Its design has particularly caught the attention of users in search of a clean and contemporary interface, making it an appealing choice for a wide range of individuals.

    1. Toolbar:
      Froala’s innovative toolbar ingeniously organizes the vast array of features into four distinct and conveniently grouped context categories: Text, Block, Media, and More. By using this simple yet intuitive toolbar, your navigation through the editor becomes effortless. You still have the option to customize it displaying only the toolbar buttons you needed.
    2. Responsive UI
      The Froala toolbar takes user experience to a whole new level with its seamless and user-friendly design. It cleverly adapts to your screen width, ensuring a perfect fit for any device. It’s like having a personal assistant that knows exactly what buttons you need the most. With just one click, you can access a plethora of features that are neatly organized, making content editing a breeze. Whether you’re on a tablet or a phone, the Froala toolbar guarantees optimal navigation and editing, regardless of screen size. On the other hand, TinyMCE maintains its toolbar buttons but struggles to adjust the toolbar width based on screen size, often leading to the annoyance of a horizontal scrollbar. This cluttered layout can be a real hassle for users trying to find specific buttons, ultimately slowing down their content editing process. Choose Froala and enjoy an efficient and hassle-free editing experience!
  5. Feature quality:
    It is crucial to understand that even if two editors have a feature with identical or similar names, their functionalities may differ. This emphasizes the importance of testing each feature in both editors instead of assuming they will produce equivalent results. For instance, when we examined how each editor handles content pasted from third-party tools, Froala effectively maintained the pasted content styles. On the other hand, TinyMCE, which named its feature “PowerPaste” and made it a premium feature, failed to do so. View the comparison results here.
  6. Other reasons
    Many reasons could make users migrate from TinyMCE to Froala. Share your thoughts in the comments section and let us know why you are considering migrating from TinMCE to Froala.

Migration Fron TinyMCE to Froala

How to migrate from TinyMCE to Froala in a React app?

The migration from TinyMCE to Froala is easy and straightforward. Follow these steps for a hassle-free process:

Uninstall TinyMCE Vue NPM Package

the initial task would involve uninstalling Tinymce from your application. In case you are using npm, you can execute the following command within your local project directory to successfully uninstall Tinymce

npm uninstall -g @tinymce

This will remove the TinyMCE React package as well as remove it from the application’s list of dependencies.

Install Froala React NPM Package

The next step in transitioning from TinyMCE to Froala is to install the Froala React NPM package in the application. To install Froala, use the following command:

npm install react-froala-wysiwyg

After the installation process is completed, you can find the react-froala-wysiwyg folder inside your npm_modules folder.

Replace TinyMCE with Froala in your components

The final step involves replacing any references to TinyMCE in your components with Froala.

Remove TinyMCE component Import statements

Search for the line

import { Editor } from "@tinymce/tinymce-react";

and replace it with the import of Froala component, stylesheets, and required plugins

// Require Editor CSS files.
import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/css/froala_editor.pkgd.min.css';

// Import all Froala Editor plugins
// Note: you can import a single plugin if needed
import 'froala-editor/js/plugins.pkgd.min.js';


//import Froala component
import FroalaEditorComponent from 'react-froala-wysiwyg';

Substitute all instances of TinyMCE with Froala

Search for <Editor which defines the TinyMCE component inside the template files and replaces it with the <FroalaEditorComponent. The two components have different tags. Therefore, it is important to replace these tags. Here is a list of TinyMCE tags and how we should handle them when migrating to Froala.

Before we start, let us consider an example of the TinyMCE Editor component:

class App extends Component {

constructor() {

  super();

}

render() {

 return (

   <Editor

     apiKey="limjfdlb66u3w96h1skw5m93kdvmf55zt4ohb3ol4jeb3q6m"

     cloudChannel='5-stable'

     disabled={false}

     initialValue='test initialValue'

     inline={false}

     onEditorChange={ }

     plugins=''

     tagName='div'

     textareaName=''

     toolbar=''

     value=''

     outputFormat='html'

     init={{

         height: 500,

         menubar: false,

         plugins: [

                   'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak', 'searchreplace', 'wordcount', 'visualblocks', 'visualchars', 'code', 'fullscreen', 'insertdatetime', 'media', 'table', 'emoticons', 'template', 'help'

                  ],

         toolbar: 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullscreen | forecolor backcolor emoticons | help',

     }}

   />

  );

 }

}

render(<App />, document.getElementById('root'));

Some of the tags will no longer be needed when migrating to Froala. Go ahead and remove them directly. they are:

  • api-key
  • cloudChannel
  • disabled
  • output-format
  • scriptLoading
  • tinymceScriptSrc
  • rollback
  • textareaName

For other tags:

id

This tag is used in both components to define the “id” attribute of the element that the editor is initialized on; therefore, we keep it as it is.

init

TinyMCE uses this property for setting the editor options. for example:

 

<editor

init = {{
        width: 600,
        height: 300,
        plugins: [

            'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak', 'searchreplace', 'wordcount', 'visualblocks', 'visualchars', 'code', 'fullscreen', 'insertdatetime', 'media', 'table', 'emoticons', 'template', 'help'

        ],

        toolbar: 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullscreen | forecolor backcolor emoticons | help',

        menu: {

            favs: {
                title: 'My Favorites',
                items: 'code visualaid | searchreplace | emoticons'
            }

        },

        menubar: 'favs file edit view insert format tools table help',

        content_css: 'css/content.css'

    }}

/>

When migrating to Froala, find the equivalent Froala API option and use it inside the config parameter of the Froala component

<FroalaEditorComponent
config = {{
        width: 600,
        height: 300,
        pluginsEnabled: [
            'lists', 'link', 'image', 'imageManager', 'charCounter', 'fullscreen', 'lineBreaker', 'codeBeautifier', 'codeView', 'colors', 'draggable', 'video', 'table', 'emoticons', 'wordPaste'
        ],
        toolbarButtons: {
            'moreText': {
                'buttons': ['bold', 'italic', 'underline', 'strikeThrough', 'clearFormatting']
            },
            'moreParagraph': {
                'buttons': ['alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', 'formatOL', 'formatUL', 'paragraphFormat', 'paragraphStyle', 'lineHeight', 'outdent', 'indent', 'quote']
            },
            'moreRich': {
                'buttons': ['insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'insertHR']
            },
            'moreMisc': {
                'buttons': ['undo', 'redo', 'fullscreen', 'selectAll', 'html', 'help'],
                'align': 'right',
                'buttonsVisible': 2
            }
        }
    }}
/>

In case the selector property is defined in TinyMCE init, this should be passed to the tag prop of the Froala component as it represents the HTML element where the editor will be initialized at.

For example, the below code

<editor

init = {{

        selector: 'textarea',

        width: 600,

        height: 300,

        menu: {

            favs: {
                title: 'My Favorites',
                items: 'code visualaid | searchreplace | emoticons'
            }

        },

        menubar: 'favs file edit view insert format tools table help',

        content_css: 'css/content.css'

    }}

/>

Should be converted to

<FroalaEditorComponent

tag = 'textarea'

config = {{

        width: 600,

        height: 300,

    }}

/>
inline

Used by TinyMCE to set the editor to inline mode. In Froala, set the toolbarInline: true inside the config tag options object.

Example:

<editor

   inline={true}

/>

This will be converted to

<FroalaEditorComponent

   config={{toolbarInline: true}}

/>
tagName

Is an optional prop to define the HTML element for the editor in the inline mode instead of using selector inside the init prop.

When you are migrating to Froala, the tagName value should be passed to the tag prop for the Froala component.

For example, the below code

<editor

inline={true}

tagName='div'

/>

Should be converted to

<FroalaEditorComponent

tag='div'

config={{toolbarInline: true}}

/>
initialValue

The initial content of the editor when the editor is initialized. Assign the initial value to the “model” prop for the Froala component.

Example

<Editor

initialValue='<p>Once upon a time...</p>'

/>

This will be converted to

<FroalaEditorComponent

tag='div'

model="<p>Once upon a time...</p>"

/>
plugins

Used to include plugins for the editor. In Froala, set the pluginsEnabled API option to the equivalent Froala plugins and add it within the config prop.

It is important to note that certain core functionalities of TinyMCE are implemented through plugins in Froala; while some functionalities provided by Froala plugins are already available by default in TinyMCE.

For example, TinyMCE has font size as a core function, whereas a Froala plugin is required to add this option.

Example

<Editor

plugins="emoticons wordcount help code lists"

/>

Will converted to

<FroalaEditorComponent

config={{ pluginsEnabled: ['emoticons', 'charCounter', 'help', 'codeView', 'lists'] }}

/>
Toolbar

Used to set the editor toolbar buttons. while migrating your code to Froala, configure the Froala toolbarButtons API option with the desired buttons and add it to the config prop.

In Froala, you can also set the toolbarButtonsMD, toolbarButtonsSM, and toolbarButtonsXS API options to customize the toolbar buttons based on the screen size.

Example:

<editor

 toolbar="bold italic underline code"

/>

Will be converted to

<FroalaEditorComponent 
config={{ toolbarButtons: ['bold', 'italic', 'underline', 'html'] }}
/>
 Events

Examine the events being used and locate their corresponding names in the Froala API events list. It may also be necessary to alter the function assigned to the event. In this case, some Froala API methods can be used to achieve the desired functionality.

Example:

<Editor onClick={this.handlerFunction} />

Will be converted to

<FroalaEditorComponent config={{ events: { 'click':handlerFunction } }} />
Full Code Example

Considering all these changes, now let’s see an example of how the code will change after migrating the TinyMCE React component to the Froala React component.

import React, { Component } from 'react';
import { render } from 'react-dom';
import { Editor } from "@tinymce/tinymce-react";

class App extends Component {
    constructor() {
        super();
    }

    render() {
        return ( <Editor
           apiKey = "limjfdlb66u3w96h1skw5m93kdvmf55zt4ohb3ol4jeb3q6m"
            cloudChannel = '5-stable'
            disabled = {
                false
            }
            initialValue = 'test initialValue'
            inline = {
                false
            }
            onEditorChange = {}
            plugins = ''
            tagName = 'div'
            textareaName = ''
            toolbar = ''
            value = ''
            outputFormat = 'html'
            init = {{
                    height: 500,
                    menubar: false,
                    plugins: [

                        'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak', 'searchreplace', 'wordcount', 'visualblocks', 'visualchars', 'code', 'fullscreen', 'insertdatetime', 'media', 'table', 'emoticons', 'template', 'help'

                    ],

                    toolbar: 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullscreen | forecolor backcolor emoticons | help',
                }}
            />
        );
    }
}

render( < App / > , document.getElementById('root'));

 

This will be converted to

import React, { Component } from 'react';
import { render } from 'react-dom';

// Require Editor CSS files.
import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/css/froala_editor.pkgd.min.css';

// Import all Froala Editor plugins
// Note: you can import single plugin if needed
import 'froala-editor/js/plugins.pkgd.min.js';

//import Froala component
import FroalaEditorComponent from 'react-froala-wysiwyg';

class App extends Component {
    constructor() {
        super();
    }

    render() {
        return ( <FroalaEditorComponent
            model = "test initialValue"
            tag = "div"
            init = {
                {
                    Key: "***", //Editor Key
                    height: 500,
                    pluginsEnabled: [
                        'lists',
                        'link',
                        'image',
                        'imageManager',
                        'charCounter',
                        'fullscreen',
                        'lineBreaker',

                        'codeBeautifier',
                        'codeView',
                        'colors',
                        'draggable',
                        'video',
                        'table',
                        'emoticons',
                        'wordPaste',
                    ],

                    toolbarButtons: {
                        moreText: {
                            buttons: [
                                'bold',
                                'italic',
                                'underline',
                                'strikeThrough',
                                'clearFormatting',
                            ],
                        },

                        moreParagraph: {
                            buttons: [
                                'alignLeft',
                                'alignCenter',
                                'formatOLSimple',
                                'alignRight',
                                'alignJustify',
                                'formatOL',
                                'formatUL',
                                'paragraphFormat',
                                'paragraphStyle',
                                'lineHeight',
                                'outdent',
                                'indent',
                                'quote',
                            ],
                        },

                        moreRich: {
                            buttons: [
                                'insertLink',
                                'insertImage',
                                'insertVideo',
                                'insertTable',
                                'emoticons',
                                'insertHR',
                            ],
                        },

                        moreMisc: {
                            buttons: [
                                'undo',
                                'redo',
                                'fullscreen',
                                'selectAll',
                                'html',
                                'help',
                            ],

                            align: 'right',

                            buttonsVisible: 2,
                        },
                    },
                }
            }
            />
        );
    }}

render( < App / > , document.getElementById('root'));
 Still Need Help?

Are you using custom plugins? This tutorial will help you to migrate them to Froala.

For more information, we check our migration from TinyMCE to the Froala feature matching guide.

With these implementations, your transition from TinyMCE to Froala should be complete!

Testing and Verifying Your Changes

After switching from TinyMCE to Froala, check all updates are functioning properly. Test the editor function and confirm that the application works the same or better than before.

Conclusion

Integrating Froala into your React app is a seamless process that will not only simplify your editing tasks but also boost the productivity of your React app. With Froala, you gain access to a wide range of comprehensive tools designed specifically for efficient rich text editing. Switch from TinyMCE to Froala now and leverage the robust features that define Froala.

Maximize User Experience with Froala WYSIWYG Editor – part 1

Froala's tips and tricks

Froala is a great WYSIWYG editor that is used by numerous users to create rich content. Developers use its powerful API to create an intuitive editing experience specific to their project usage case. You can customize the Froala WYSIWYG editor in a variety of ways to meet the needs of your project. In this article, we will discuss some tips and tricks to enhance your users’ usage and productivity.

Edit Link Attributes

Froala is used to edit links through a simple pop-up. By default, the pop-up only allows you to set the URL and the text of the link with an option to open the link in a new tab. Your users could be disappointed if they would like to edit more link attributes such as the title, rel, and class attributes. You may not know, but you can display more attributes in the Froala edit link pop-up easily using the link attributes API option. This option accepts an object with additional attributes that could be customized for a link.

In case you want to add the ability to change the link title attribute, you’ll need to set the linkAttributes like:

new FroalaEditor('textarea.edit', {

linkAttributes: {

title: 'Enter Title'

},

});

Now, if you try to insert or edit a link in your Froala editor, you will see an additional field asking for a ‘Title’. Similarly, you can add other attributes such as the link’s rel, target, and class attributes with more control over the customization. This not only simplifies the editing process but also enhances the user experience.

Setting a Character Limit in Froala for Efficient Content Management

This tip is useful if you are using Froala as an input and want to limit the number of characters that your users can enter. Often, this is important to maintain the required number of the database field. Many developers don’t know that implementing a character limit is pretty straightforward in Froala.

You can use the charCounterMax API option to restrict your users from adding more than a specified number of characters to their content. To implement this, you need to add the charCounterMax option to your Froala editor.

new FroalaEditor('textarea.edit', {

charCounterMax: 500,

});

In this case, users cannot add over 500 characters to the content. If they try to go beyond the set limit, the editor will not accept additional characters.

You can go beyond this and provide a custom message to users when they hit the maximum limit. This can be done by customizing the charCounter.exceeded API event which is triggered when the charCounterMax value is exceeded. For simplicity, you can display an alert with a “You have exceeded the max character limit” message when the limit is reached:

new FroalaEditor('textarea.edit', {

charCounterMax: 500,

events: {

'charCounter.exceeded': function () {

alert('You have exceeded the max character limit');

},

},

});

Here, an alert will pop up once users hit the limit, helping them recognize and adjust their text to the specified character restriction.

You’re not allowed to enter more than 70 characters.

Tips and tricks - Froala

Customizing Text Color to Match Your Brand

Froala allows you to choose from a wide set of colors for text editing by default. Additionally, a text box is available for typing any Hex color code. However, there might be situations where you want to limit the color options, such as maintaining consistency with your brand identity or simplifying the user interface.

To set the limitation on text colors, you can modify the colors option in your Froala editor settings. You will need to specify the colors in an array and assign them to the colorsText API option then hide the HEX input to enter a custom color by setting the colorsHEXInput API option to false.

new FroalaEditor('textarea.edit', {

colorsText: ['#61BD6D', '#1ABC9C', '#54ACD2', '#2C82C9', '#2B272B'],

colorsHEXInput: false,

});

With this setup, users can only choose from the five different colors specified in the array when coloring their text.

Try to change the text color.

Improves the page performance with editor lazy loading

Lazy loading is a technique that allows you to defer the initialization or loading of an object or a resource until it is actually needed. Lazy loading aims to save memory and bandwidth, as it avoids loading unnecessary data or code. If you are searching for a way to lazy load Froala editor, you don’t need to look far away.

Froala supports this functionality right out of the box. You just need to set the initOnClick option in your Froala editor instance. By setting this option to true, the editor will initialize only the basic code when the page is loaded and the rest of the code when clicking in the editable area.

This can greatly improve the performance of your page, especially if you have multiple instances of the Froala editor on the same page.

new FroalaEditor('textarea.edit', {

initOnClick: true

});

Disable Right Click within the editor

For some websites or applications, disabling right-click within the editor may be necessary to avoid undesired user actions such as copying, pasting, or inspecting the HTML code. This also makes it possible to override the default browser menu with a custom one from your creation.

Fortunately, Froala provides an easy method to achieve this. By setting the disableRightClick API to true, whenever users right-click within the editor, no contextual menu will pop up.

new FroalaEditor('.selector', {

disableRightClick: true

});

Disabling this option is also recommended if you are using the inline mode and you set the toolbarVisibleWithoutSelection to Keep the editor visible next to the cursor even when there is no selection.

To create a custom action instead of the default browser context menu, you can first detect if the user right-clicked the editor by listening for the mousedown event and checking if the right mouse button was pressed, then do whatever you want. Here is an example:

new FroalaEditor('textarea.edit', {

disableRightClick: true,
events: {

'mousedown': function (e) {

if (e.which == 3) {

console.log('Right-click detected.');

}

}

},

});

In the above example, the console will log a message every time the user right-clicks within the editor.

Conclusion

Froala is an excellent WYSIWYG editor that gives you a range of customization options to suit your unique needs. With its friendly UI and rich features, it allows you to enhance the editing process and improve the overall user experience. Whether it is setting character limits, customizing text colors, lazy loading for improved performance, or disabling right-click for more control, Froala’s functionalities pay heed to every minor detail. Master these tips, and you can maximize the potential of content management with Froala.

Try experimenting with these features and witness how Froala transforms your regular content into interactive and engaging ones. Remember, the ability to adapt and customize according to your requirements is what makes an editor truly powerful. And, Froala stands out in this aspect. Start your free trial now!

Character Counter for Froala Editor in Angular App Project

Character Counter

Integrating Character Counter on Froala WYSIWYG Editor Running on an Angular App Project

Froala WYSIWYG Editor is a powerful and customizable  angular rich text editor that can enhance the text editing experience in your Angular applications.

One useful feature that you may want to add is the Character Counter plugin to keep track of the number of characters in the editor.

In this tutorial, we’ll walk you through integrating the Character Counter plugin from Froala into your Angular app editor.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  • Node.js and npm (Node Package Manager) are installed on your system.
  • Angular CLI (Command Line Interface) is installed on your machine.

If you haven’t installed it, you can do so using the following command:

npm install -g @angular/cli

Now, you can create a new Angular app using the Angular CLI:

ng new myApp

cd myApp

Replace “my-app” with your preferred app name.

Character Counter

Step 1: Installing Froala WYSIWYG Editor

In your Angular app project, navigate to the project root folder and install Froala WYSIWYG Editor using npm:

npm install angular-froala-wysiwyg

This command will install the required packages for Froala integration.

Step 2: Update index.html

Open the index.html file in your project’s src folder and add the following code inside the <head> tag:

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>MyApp</title>

  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link href="node_modules/froala-editor/css/froala_editor.pkgd.min.css" rel="stylesheet">

</head>

<body>

  <app-root></app-root>

</body>

</html>

This code includes the Froala Editor CSS stylesheet.

Step 3: Update app.module.ts

Open the app.module.ts file in your project’s src/app folder and make the following changes:

import { NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

import 'froala-editor/js/plugins.pkgd.min.js'; 

import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';


@NgModule({

  declarations: [AppComponent],

  imports: [

    BrowserModule,

    FroalaEditorModule.forRoot(),

    FroalaViewModule.forRoot(),

  ],

  providers: [],

  bootstrap: [AppComponent],

})

export class AppModule {}


In this code, we import the Froala Editor module and configure it using FroalaEditorModule.forRoot() and FroalaViewModule.forRoot().

Step 4: Update angular.json

Open the angular.json file in your project root folder and add the Froala Editor CSS styles to the “styles” array:

"styles": [

  "src/styles.css",

  "node_modules/froala-editor/css/froala_editor.pkgd.min.css",

  "node_modules/froala-editor/css/froala_style.min.css"

],

This ensures that the Froala Editor styles are included in your Angular app.

Step 5: Update app.component.html

Open the app.component.html file in your project’s src/app folder and add the following code:

<div class="content" role="main">

  <div [froalaEditor]="options" [(froalaModel)]="editorContent"></div>

</div>

This code creates a div element with the [froalaEditor] directive to initialize the Froala Editor component.

Step 6: Update app.component.ts

Open the app.component.ts file in your project’s src/app folder and replace its contents with the following code:

import { Component } from '@angular/core';

@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css'],

})

export class AppComponent {

  editorContent = '<a href="https://froala.com/">Froala Angular WYSIWYG Editor</a>';

  public options: Object = {

    events: {

      'froalaEditor.contentChanged': function () {

        console.log('Content updated!');

      }

    }

  };

}

We import the necessary Angular module and define the AppComponent class. We set the editorContent variable with the initial HTML content for the Froala Editor.

We define the options object to specify event handling.

In this example, we’ve added a content change event that logs a message when the editor’s content changes.

Step 7: Include the Character Counter plugin

To enable the character counter feature, you need to configure the options object in your component’s TypeScript file. Here’s an example:

import { Component } from '@angular/core';

@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css'],

})

export class AppComponent {

  editorContent = '<a href="https://froala.com/">Froala Angular WYSIWYG Editor</a>';

  public options: Object = {

    charCounterCount: true,

    charCounterMax: 140,

    events: {

      'froalaEditor.contentChanged': function () {

        console.log('Content updated!');

      }

    }

  };

}


In this example, we set charCounterCount to true to enable the character counter. You can also specify the charCounterMax property to define the maximum character limit for your editor.

This plugin serves a specific purpose: it enables you to limit the number of characters that users can input or edit within the WYSIWYG editor.

  • Character Limitation: The primary function of the char_counter.min.js plugin is to enforce a character limit. This is particularly useful when you want to restrict the amount of text or content that users can add to a specific area, such as a comment box, a description field, or any other input field where text input needs to be controlled.
  • Real-Time Character Count: The plugin typically provides a real-time character count feature. It counts and displays the number of characters currently entered or edited by the user. This count is often displayed near the editor, allowing users to monitor their input as they type.
  • Limit Exceedance Handling: When the user exceeds the specified character limit, the plugin can be configured to prevent further input or display a warning or error message. This ensures that users know the limit and can’t go beyond it.
  • Customization: Depending on the plugin’s capabilities and the integration into your application, you may have options to customize the appearance and behavior of the character counter, such as changing the color or style of the counter display or the error message.
  • Ease of Use: Implementing this plugin is usually straightforward. You include the plugin’s JavaScript file in your project, initialize it, specify the character limit, and set up any event handlers or display elements as needed.

Step 8: Run Your Angular App

With all the necessary changes made, you can now run your Angular app:

npm start

This command will start a development server, and your app will be available at http://localhost:4200/ by default.

Froala Character Counter plugin

Conclusion

You have successfully integrated Froala WYSIWYG Editor into your Angular app.

Now, when you navigate to your app’s URL, you will see the Froala Editor in action, complete with the initial content and event handling as configured.

The Character Counter plugin is a valuable tool for enforcing character limits and providing real-time character count feedback within a WYSIWYG HTML editor.

It helps maintain content quality, prevents excessive input, and enhances the user experience when dealing with text or content input fields in web applications.

Froala WYSIWYG Editor provides a wide range of features and customization options, allowing you to create rich text editing experiences tailored to your needs.

Explore the Froala documentation for more details on how to utilize its features in your Angular application.

Web Editing with Froala’s Special Tags in Vue App

Froala’s Special Tags in Vue

The people who are crazy enough to think they can change the world are the ones who do

— Steve Jobs.

When the Froala WYSIWYG editor idea started, many WYSIWYG editors were already on the market. The goal wasn’t to add another standard editor. We were obsessed with offering an out-of-box experience that would revolutionize web editing. It was founded on improving the drawbacks and exposing the strengths of the pre-existing editors, including TinyMCE.

From introducing the most mobile-friendly editor toolbar to being the first WYSIWYG editor with the popup with formatting controls appearing the same on mobile devices as on desktops, Froala continued pushing the boundaries in ways never seen before in the WYSIWYG editor market. With every update and new feature added, the underlying goal was to enhance the web editing process for the end-users and developers alike. Ensuring that, as Steve Jobs said, we are “the ones who do”.

Vue SDK special tags

Froala initialization modes

While other WYSIWYG editors were developed to provide the same user interface regardless of the HTML element they initialized on, Froala innovated this, making initializing the editor on different HTML elements generate a different user interface suitable for editing that element specifically.

For example, initializing the editor on the HTML <a> element will not open the full editor with the hundreds of toolbar buttons. Instead, it will display Froala’s Edit Link popup, which easily lets you change the URL and display the text of the hyperlink. This focus on user-centered design facilitated ease of interaction and enhanced the user experience tenfold.

<script>

var editor = new FroalaEditor('a#example');

</script>

If you prefer a more comprehensive editing experience, you can easily initialize the editor on a ‘textarea’ or a regular ‘div’ element.

<script>

var editor = new FroalaEditor('textarea#example');

</script>

In <img> element instance, when Froala initializes, it brings up a simple window to replace the image, adjust its alignment, insert alt text, and other relevant properties.

<script>

var editor = new FroalaEditor('img#example');

</script>

Besides the <img> and <a> HTML tags, it also outputs a specific user interface when used on the <button> and <input> elements.

This flexibility to adopt initiative UI depends on the specific HTML element it initializes upon distinguishing Froala from many of its competitors. It underlines our commitment to offering a highly personalized experience that eases and expedites the editing process for the end user.

This flexibility allows Froala to be used as a standalone Image uploader or in building a modern drag-and-drop web page builder.

How to implement initialization modes in the Vue app?

First, let us quickly recap how we can add Froala to a Vue app. It is a simple 3-step process:

  1. Install the Froala package via NPM. Use the command
    npm install vue-froala-wysiwyg

    in the terminal to download and add it to your project’s node_modules folder.

  2. After successfully installing the package, you need to import it into your main.js file. Add the code below to complete this:
    import { createApp } from "vue";
    
    import App from "./App.vue";
    
    //Import Froala Editor plugins
    
    import "froala-editor/js/plugins.pkgd.min.js";
    
    // Import Froala Editor css files.
    
    import "froala-editor/css/froala_editor.pkgd.min.css";
    
    import "froala-editor/css/froala_style.min.css";
    
    // Import Froala Editor component
    
    import VueFroala from "vue-froala-wysiwyg";
    
    const app = createApp(App);
    
    app.use(VueFroala);
    
    app.mount("#app");
  3. Finally, to display the editor, all you need to the Froala component inside your template
    <froala tag=’textarea’ :config="config"></froala>

    See the following complete example:

    <template>
      <img alt="Vue logo" src="./assets/logo.png">
      <froala id="edit" :tag="'textarea'" :config="config" v-model:value="model"></froala>
    </template>
    
    <script>
    
    export default {
      name: 'App',
      data () {
        return {
          config: {
              toolbarButtons: {
    
                'moreText': {
    
                  'buttons': [ 'italic', 'underline', 'bold', 'strikeThrough', 'subscript', 'superscript', 'fontFamily', 'fontSize', 'textColor', 'backgroundColor', 'inlineClass', 'inlineStyle', 'clearFormatting']
    
                },
    
                'moreParagraph': {
    
                  'buttons': ['alignLeft', 'alignCenter', 'formatOLSimple']
    
                },
    
                'moreRich': {
    
                  'buttons': ['insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome', 'specialCharacters', 'embedly', 'insertFile', 'insertHR']
    
                },
    
                'moreMisc': {
    
                  'buttons': ['undo', 'redo', 'fullscreen', 'print', 'getPDF', 'spellChecker', 'selectAll', 'html', 'help'],
    
                  'align': 'right',
    
                  'buttonsVisible': 2
    
                }
    
              },
            events: {
              initialized: function () {
                console.log('initialized')
              }
            }
          },
          model: '<i>Edit Your Content Here!</i>'
        }
      }
    }
    </script>
    
    <style>
    #app {
      font-family: Avenir, Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    </style>
    

The Froala Vue component attributes are:

  •  `tag` – This should match the HTML element on which you want to initialize the editor. By default, the tag is ‘textarea’. We set its value to ‘a’, ‘img’, ‘button’, or ‘input’ which we call the special tags, to implement the other initialization modes.
  •  `config` – This is an optional attribute where you can pass the Froala configuration options.
  •  v-model – Using this with the ‘froala’ component, Vue can handle automatic synchronization between the component and its underlying data model. This proves useful when integrating Froala alongside other components within your Vue application, as it promotes interactive and dynamic content creation.

Special tags

The Froala editor Vue special tags are img, button, input, and a tags. using these tags you can have different initialization modes. In this case, there are some considerations:

  1. The model must be an object containing the attributes for your special tags.
  2. The model can contain a special attribute named innerHTML which inserts innerHTML in the element, for example, If you are using ‘button’ tag, you can specify the button text like this
    buttonModel: {
    
    innerHTML: 'Click Me'
    
    }
  3. Froala provides an additional option when using special tags. This option is
    vueIgnoreAttrs
    : (default: null) This option is an array of attributes that you want to ignore when the editor updates the v-model:

    config: {
    
    vueIgnoreAttrs: ['class', 'id']
    
    }

Examples of using special tags:

  1. Img

<template>
  <froala
    id="edit"
    :tag="'img'"
    :config="imageOptions"
    v-model:value="imgModel"
  ></froala>
</template>

<script>
export default {
  name: "app",

  data() {
    return {
      imgModel: {
        src: "https://fakeimg.pl/350x200/?text=Click%20on%20me",
      },

      imageOptions: {
        vueIgnoreAttrs: ["style"],
      },
    };
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;

  -webkit-font-smoothing: antialiased;

  -moz-osx-font-smoothing: grayscale;

  text-align: center;

  color: #2c3e50;

  margin-top: 60px;
}
</style>

In the above example,  we have set the :tag attribute to “img”.

<froala :tag="img" :config="imageOptions" v-model:value="imgModel"></froala>

The model must be an object containing the attributes for your special tags. In the case of the img element, you must declare the “src“ attribute so you can render the image.

imgModel: {

src: "https://fakeimg.pl/350x200/?text=Click%20on%20me",

}

Note, the model will change as the attributes change during usage.

and we used the special option vueIgnoreAttrs to preventStyle” from being updated in the model.

imageOptions: {

vueIgnoreAttrs: ["style"],

},

When you run your Vue app, you’ll see an image. Clicking on it will open the Froala edit image popup, allowing you to replace the image, add ALT text, insert a caption, and more.

  1. Button

<template>
  <froala id="edit" :tag="'button'" v-model:value="buttonModel"></froala>
</template>

<script>
export default {
  name: "app",

  data() {
    return {
      buttonModel: {
        innerHTML: "Click Me",
      },
    };
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;

  -webkit-font-smoothing: antialiased;

  -moz-osx-font-smoothing: grayscale;

  text-align: center;

  color: #2c3e50;

  margin-top: 60px;
}
</style>

In the above example, you can see we have set the :tag attribute to “button”.

<froala id="edit" :tag="'button'" v-model:value="buttonModel"></froala>

We used the model’s special attribute “innerHTML” to specify the button

buttonModel: {

innerHTML: 'Click Me'

},

As the editor changes the button text, the innerHTML attribute from buttonModel model will change too.

When you run your Vue app, you’ll see a button with the text ‘Click me‘. Clicking on it will open a popup to update the button text.

  1. input tag

<template>
  <froala id="edit" :tag="'input'" v-model:value="inputModel"></froala>
</template>

<script>
export default {
  name: "app",

  data() {
    return {
      inputModel: {
        placeholder: "I am an input!",
      },
    };
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;

  -webkit-font-smoothing: antialiased;

  -moz-osx-font-smoothing: grayscale;

  text-align: center;

  color: #2c3e50;

  margin-top: 60px;
}
</style>

In the above example, you can see we have set the :tag attribute to “input”.

<froala id="edit" :tag="'input'" v-model:value="inputModel"></froala>

We used the model to set the input placeholder attr

inputModel: {

placeholder: 'I am an input!'

},

This will show an input field with the placeholder text “I am an input!”. Clicking on it will open a popup to update the input text.

  1. a tag

<template>
  <froala id="edit" :tag="'a'" v-model:value="linkModel"></froala>
</template>

<script>
export default {
  name: "app",

  data() {
    return {
      linkModel: {
        href: "https://www.froala.com/wysiwyg-editor",
      },
    };
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;

  -webkit-font-smoothing: antialiased;

  -moz-osx-font-smoothing: grayscale;

  text-align: center;

  color: #2c3e50;

  margin-top: 60px;
}
</style>

In the above example, you can see we have set the :tag attribute to “a”.

  <froala id="edit" :tag="'a'" v-model:value="linkModel"></froala>

We used the model to assign the href attribute to the desired URL.

      linkModel: {
        href: "https://www.froala.com/wysiwyg-editor",
      },

This will show a link named “My link” and has the URL “https://www.froala.com/wysiwyg-editor”. When this link is clicked, the Froala edit link popup will open allowing the link’s properties to be updated.

Easily edit multiple HTML elements

These examples illustrate how you can simplify the task of revising HTML tags in your Vue app while maintaining a dependable link to v-model values. This enables faster, more reactive application updates with minimal effort. Whether it’s tweaking an image property, editing button text, adjusting a link, or updating an input text, Froala provides a seamless and intuitive editing experience. By utilizing special tag attributes in combination with v-model, you can instantly reflect changes made in the editor on your Vue App. The potential of this feature paves the way for more flexible, user-friendly applications enhanced by real-time responses and modifications.

Start using the Froala editor Vue SDK now.

Learn how to migrate From TinyMCE to Froala.

Here are several Froala Vue WYSIWYG editor examples you can try:

Effortlessly Migrate from TinyMCE to Froala in Your Vue App

Migration from TinyMCE to Froala in a Vue app

When we released Froala 4.1, which supports the LTS Vue version and many other popular JS frameworks, we anticipated significant migration from TinyMCE to Froala. Whether you are a fan of Froala or currently experiencing issues with TinyMCE and looking to switch to Froala for your Vue app, this article aims to provide you with a smooth and efficient transition process. We will guide you through every step, starting from removing TinyMCE to installing and configuring the Froala editor. By the end of this article, you should be able to switch your TinMCE editor to Froala with confidence and ease.

 Why do users migrate from TinyMCE to Froala?

There are several reasons for users to migrate from TinyMCE to Froala, such as:

  1. User Interface:
    Many users like the Froala UI. From the flat design to eye-catching SVG icons, Froala clearly stands out. The design of Froala Editor attracts many users who want a clean and modern interface.

    1. Smart Toolbar:
      The Froala Editor boasts an ingenious smart toolbar that organizes its myriad of features into four conveniently grouped context categories: text, block, media, and more. This simple yet intuitive toolbar ensures effortless navigation, as every feature is effortlessly locatable.
    2. Responsive:
      The Froala Toolbar offers a seamless and user-friendly experience by automatically adapting to the user’s screen width. It intelligently displays only the most commonly used buttons, while hundreds of other features are one click away. This is particularly useful for users working on tablets or phones, as it ensures optimal navigation and editing regardless of the screen size of the device.
      In contrast, TinyMCE maintains the toolbar buttons but adjusts the toolbar width based on the screen size, often resulting in the need for a horizontal scrollbar. This can make it challenging for users to locate specific buttons among the clutter, ultimately slowing down the content editing process.
  2. Used Technology:
    Both editors are Javascript editors but handle content differently. This results in a different HTML output for each editor. Moreover, these editors possess different API structures, which affects how developers can work with them. Many developers prefer easy use of the Froala API. This allows for easy customization of the editor’s function and the creation of custom elements or plugins.
  3. Transparent Pricing:
    Froala plans have a clear pricing model. There are no hidden costs, all Froala’s plugins are included, and there is no limitation on the editor’s usage. In contrast, TinyMCE plans are limited to a certain number of page loads. For example, their “Free“ plan is restricted to 1000 page loads.
    If a small-scale company with 10 users and each user loads a page containing the TinyMCE editor 10 times per day, they will reach the maximum editor-load limit in just 10 days. To continue using TinyMCE, they would need to pay $40 for another 1000 loads, resulting in a monthly cost of $80 or an annual cost of $960. This is actually higher than the cost of the Froala Professional plan.
    In addition, the free TinyMCE plan is limited to one domain, lacks access to all plugins, and does not include professional support.
    (Note: The mentioned prices are due date:8th of September 2023. prices could change later.)
  4. Feature quality:
    It is important to note that even if both editors share a feature with the same or similar name, their behaviors may vary. This highlights the significance of testing each feature in both editors, rather than assuming that they will deliver the same level of quality. For instance, we conducted a thorough examination of how each editor pastes content from third-party tools. However, TinyMCE named its feature “PowerPaste“ and made it a premium feature (Included on their Perfossional plan), yet it failed to maintain the pasted content styles as effectively as Froala did. To view the detailed results of our comparison, click here.
  5. Multiple Vue components:
    Unlike TinyMCE, which only has a single Vue component for rendering the editor, Froala SDK offers multiple Vue components. In addition to the component for rendering the editor itself, Froala provides a component for rendering editor content outside the editor to make it easy to display the editor content for viewers. Furthermore, the Froala component enables a special rendering mode for the editor on the img, button, input, and <a> tags.
  6. Other reasons
    There are many reasons that we will not cover here because we want to focus on learning how to migrate from TinyMCE to Froala. Share your thoughts in the comments section and let us know why you are migrating from TinMCE to Froala.

Migration from TinyMCE to Froala

How to migrate from TinyMCE to Froala in a Vue app?

The migration from TinyMCE to Froala is easy and straightforward. Follow these steps for a hassle-free process:

Uninstall TinyMCE Vue NPM Package

The first step in migrating from TinyMCE to Froala in your Vue application involves uninstalling TinyMCE. Uninstalling TinyMCE involves removing it from the application’s list of dependencies as well as deleting any references to it in your project.

Use your package manager to uninstall TinyMCE. If you are using npm, you can run the following command in your local project directory to uninstall TinyMCE:

npm uninstall -g @tinymce

Inside your npm_modules folder, you should find the “@tinymce“ folder is removed or empty.

Install Froala Vue NPM Package

The next step in transitioning from TinyMCE to Froala is to install the Froala Vue NPM package in the application. To install Froala, use the following command:

npm install vue-froala-wysiwyg

After the installation process completes, you can find the “vue-froala-wysiwyg” folder inside your npm_modules folder.

Replace TinyMCE with Froala in your components

The final step involves replacing any references to TinyMCE in your components with Froala.

Begin by deleting the import component statements associated with Tinymce and importing the Froala component instead. It is important to note that there is a distinction in how each editor’s component is imported. Usually, the Tinymce component is imported within a <script use> tag in the specific component where Tinymce will be utilized. On the other hand, it is preferable to import the Froala Vue component in the main.js file, where we use app.use() to globally install and load all Froala components throughout the entire Vue application.

Remove TinyMCE component

Search for the line

import Editor from '@tinymce/tinymce-vue';

and remove all the instances from your Vue applications.

Import Froala in your Vue App

In order to use Froala in your Vue application, it must be properly integrated. This involves importing the Froala WYSIWYG editor styles files into your application.

Open the main.js file and Import the Froala component, plugin files, and its styles using these lines of code:

//Import Froala Editor plugins

import 'froala-editor/js/plugins.pkgd.min.js';

// Import Froala Editor css files.

import 'froala-editor/css/froala_editor.pkgd.min.css';

import 'froala-editor/css/froala_style.min.css';

// Import Froala Editor component

import VueFroala from 'vue-froala-wysiwyg';

Once imported, make sure to pass it in the app.use() method.

app.use() is used to install the Froala components to the entire Vue application, not to a single component

const app = createApp(App);

app.use(VueFroala);

app.mount('#app');

Substitute all instances of TinyMCE with Froala in your template files.

Search for <Editor which defines the TinyMCE component inside the template files and replace it with the <froala. The two components have different tags. Therefore, it is important to replace these types of tags. Here is a list of TinyMCE tags and how we should handle them when migrating to Froala.

Before we start, let us consider an example of the TinyMCE Editor component:

<Editor

api-key="your-api-key"

cloud-channel="6"

:disabled=false

id="uuid"

:init="{

selector: 'textarea',

plugins: 'lists link image paste help wordcount',

toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | help'

}"

initial-value="Once upon a time..."

:inline=true

@click="handlerFunction"

/>

Some of the tags will no longer be needed when migrating to Froala. Go ahead and remove them directly. they are:

      • api-key
      • cloud-channel
      • disabled
      • output-format
      • tinymce-script-src
      • model-events
id

This tag is used in both components; therefore, we keep it as it is.

tag-name

Is used to define the HTML element for the editor in the inline mode. Replace it with :tag. If it is not defined use :tag=textarea

init

This is the object sent to the tinymce.init method to initialize the editor. It contains the editor options. for example

<editor

:init="{

selector: '#myTextarea',

width: 600,

height: 300,

plugins: [

'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak',

'searchreplace', 'wordcount', 'visualblocks', 'visualchars', 'code', 'fullscreen', 'insertdatetime',

'media', 'table', 'emoticons', 'template', 'help'

],

toolbar: 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | ' +

'bullist numlist outdent indent | link image | print preview media fullscreen | ' +

'forecolor backcolor emoticons | help',

menu: {

favs: { title: 'My Favorites', items: 'code visualaid | searchreplace | emoticons' }

},

menubar: 'favs file edit view insert format tools table help',

content_css: 'css/content.css'

}"

/>

The most commonly used options are selector, plugins, toolbar, menu, and menubar. We will cover the equivalent for plugins and toolbar options in Froala below.

Because Froala displays only a toolbar, menu and menubar options will be removed.

For the selector option, add its value to the :tag attribute.

For other options like height, find the equivalent Froala API option and use it instead. In this case, Froala also uses the height option to set the editor height.

initial-value

The initial content of the editor when the editor is initialized. Put the initial value inside the component tag.

Example: using initial-value
<editor

initial-value="Once upon a time..."

/>

This will be converted to

<froala>Once upon a time...</froala>
v-model

Replace it with v-model:value

inline

Used to set the editor to inline mode. In Froala, set the toolbarInline: true inside the :config tag options object.

Example:
<editor

:inline=true

/>

This will converted to

<froala

:config="{toolbarInline: true}"

></froala>
plugins

Used to include plugins for the editor. In Froala, set the pluginsEnabled API option to the equivalent Froala plugins and add it to the :config tag options object.

It is important to note that certain core functionalities of TinyMCE are implemented through plugins in Froala; while some functionalities provided by Froala plugins are already available by default in TinyMCE.

For Example, TinyMCE has font size as a core function, whereas a Froala plugin is required to add this option.

Example:
<editor

plugins="emoticons wordcount help code lists"

/>

It will be converted to

<froala   :config="{ pluginsEnabled: ['emoticons', 'charCounter', 'help', 'codeView', 'lists'] }" > </froala>
toolbar

Used to set the toolbar for the editor. In Froala, set the toolbarButtons API option with the equivalent Froala toolbar buttons and add it to the :config tag options object.

In Froala, you can also set the toolbarButtonsMD, toolbarButtonsSM, and toolbarButtonsXS API options to customize the toolbar buttons based on the screen size.

While the toolbar attribute in the <editor> component accepts a string, the Froala toolbarButtons options accept arrays.

Example:
<editor

toolbar="bold italic underline code"

/>

Will converted to

<froala :config="{ toolbarButtons: ['bold', 'italic', 'underline', 'html'] }" > </froala>
Events

In the TinyMCE <editor> component, you will find event names declared after the @ symbol, such as:

<editor @click="handlerFunction" />

However, in Froala, Events are declared in the event objects inside the option object that is passed to the tag attribute.

So to migrate events, you will need to check which events are used and find the equivalent event name from the Froala API events list. It may also be necessary to alter the function assigned to the event. In this case, some Froala API methods can be used to achieve the desired functionality.

Example: migrating events

In TinyMCE:

<editor    @click="handlerFunction" />

In Froala:

<froala :config="{ events: { 'click':handlerFunction } }"  ></froala>
Full Example

Considering all these changes, now let’s see an example of how the <Editor> tag in TinyMCE will look after modification to <froala> in our Vue template.

Considering the following TinyMCE config

<Editor

cloud-channel=6

disabled =false

id="uuid"

:disabled=false

api-key="no-api-key"

:init="{

selector: 'textarea',

height: 300,

}"

plugins="emoticons wordcount help code lists"

toolbar="bold italic underline code"

initial-value="Once upon a time..."

:inline=true

@click="handlerFunction"

/>

The corresponding Froala config will be as follows:

<froala

tag='textarea'

:config="{

heightMax: 300,

pluginsEnabled: ['emoticons', 'charCounter', 'help', 'codeView', 'lists'],

toolbarButtons: [['bold', 'italic', 'underline'],['html']],

toolbarInline: true,

events: { 'click':handlerFunction }

}"

:id="uuid"

>Once upon a time...</froala>
Still Need Help?

Are you using custom plugins? This tutorial will help you to migrate them to Froala.

For more information, we check our migration from TinyMCE to the Froala feature matching guide.

With these implementations, your transition from TinyMCE to Froala should be complete!

Testing and Verifying Your Changes

After migrating from TinyMCE to Froala, ensure that all changes are working correctly. Test all editor features and verify whether the application behaves the same or better than before.

Conclusion

By switching from TinyMCE to Froala, you can now leverage the robust features that define Froala.

Integrating Froala into your Vue app is smooth, and straightforward, and actually enhances the productivity of your Vue app. Froala provides you with comprehensive tools to tackle rich text editing tasks efficiently. So make the switch and watch your Vue application thrive with Froala.

Inline React Editor: Using Froala’s Inline Mode Guide

Inline React Editor

In web development, creating a seamless editing experience is often a necessity.

Whether you’re building a content management system (CMS), a blog platform, or a collaborative document editor, providing a feature-rich and intuitive inline text editor can enhance the user experience.

One tool that stands out for this purpose is the Froala WYSIWYG Editor, which offers an Inline React Editor mode that allows you to embed rich text editing capabilities into your React applications.

In this article, we’ll delve into how to use Froala’s Inline Mode in a React App project.

Froala inline mode in React

What is the Froala WYSIWYG Editor?

Before diving into the intricacies of implementing Froala’s Inline Mode in a React-based application, it’s crucial to understand what the Froala WYSIWYG Editor brings to the table.

Froala is more than just another text editor; it’s a powerful JavaScript library designed to deliver a high-quality, user-friendly WYSIWYG (What You See Is What You Get) experience. Unlike traditional text editors, Froala allows for seamless text editing and formatting right within web applications, mimicking the features and capabilities of a full-fledged word processor.

One of the standout features of Froala is its flexibility.

Spotlight: Inline Mode

One feature that deserves special mention is Froala’s Inline Mode. This mode allows you to embed the editor directly within the text of your web page. Instead of switching to a separate editing interface, users can edit text on-the-fly, making the user experience more intuitive and less disruptive.

Setting Up Your React App

To get started with using Froala’s Inline Mode in a React application, you first need to set up your project.

If you haven’t already created a React app, you can do so using Create React App or your preferred method.

Once your project is ready, follow these steps to integrate Froala into your app:

Step 1: Installation

You can install the Froala WYSIWYG Editor for React by running the following command in your project directory:

npm install react-froala-wysiwyg --save

Step 2: Adding the Editor

In the component where you want to use the Froala Inline Editor, import Froala features and code the component:

import "froala-editor/css/froala_style.min.css";

import "froala-editor/css/froala_editor.pkgd.min.css";

import FroalaEditorComponent from "react-froala-wysiwyg";

function App() {

  let model = '<p><a href="https://froala.com">Froala WYSIWYG Editor</a></p>';

  return (

    <div id="froala-editor">

          <h1>Froala WYSIWYG Editor </h1>

          <h2>Tutorial about Inline React Editor</h2>

      <FroalaEditorComponent

        tag="textarea"

        model={model}

        config={{

        }}

      />

    </div>

  );

}

export default App;

In this code snippet, we code the necessary components and plugins for the Froala editor.

Froala React editor

The toolbarInline: true configuration option is what enables the Inline Mode.

    <FroalaEditorComponent

        tag="textarea"

        model={model}

        config={{

          toolbarInline: true

        }}

  />

Inline React editor

Understanding the final component line-by-line

This code is a simple React application that uses the Froala WYSIWYG Editor to render a rich text editor on a web page. Let’s break down the code step by step:

import "froala-editor/css/froala_style.min.css";

import "froala-editor/css/froala_editor.pkgd.min.css";

These lines import the necessary CSS stylesheets for the Froala WYSIWYG Editor. These styles define the appearance and layout of the editor.

import FroalaEditorComponent from "react-froala-wysiwyg";

This line imports the FroalaEditorComponent from the “react-froala-wysiwyg” library.

This component is a React wrapper for the Froala WYSIWYG Editor, allowing you to integrate it into your React application.

Define the App component:

function App() {

This is a functional React component named App. It’s the entry point of your application.

let model = '<p><a href="https://froala.com">Froala WYSIWYG Editor</a></p>';

Here, a string variable named model is defined, which contains HTML content. This HTML content will be displayed in the Froala WYSIWYG Editor when the component is rendered.

Render the component:

return (

<div id="froala-editor">

<h1>Froala WYSIWYG Editor</h1>

<h2>Tutorial about Inline React Editor</h2>




<FroalaEditorComponent

tag="textarea"

model={model}

config={{

toolbarInline: true

}}

/>

</div>

);

The return statement contains JSX code that defines the structure of the rendered component.

Inside the div with the id “froala-editor,” there are two heading elements (h1 and h2) providing some context about the editor.

The FroalaEditorComponent is used to render the Froala WYSIWYG Editor itself. It is configured as follows:

  • tag="textarea": This specifies that the editor should be rendered as a textarea element.
  • model={model}: This sets the initial content of the editor to the HTML content stored in the model variable.
  • config: This is an object that specifies configuration options for the editor. In this case, it sets toolbarInline to true, indicating that the toolbar should be displayed inline with the editor.

Export the App component:

export default App;

This exports the App component so that it can be used in other parts of the application or imported into other files.

In summary, this code sets up a simple React application that displays a Froala WYSIWYG Editor with some initial HTML content.

Users can interact with the editor to edit and format text as needed. The editor’s appearance and behavior are controlled by the configuration options provided in the config object.

You can further customize the editor by adding or removing plugins and adjusting configuration settings to suit your project’s requirements.

Customizing the Inline React Editor

The power of the Froala Inline Mode lies in its customizability. You can tailor the editor’s behavior, appearance, and functionality to align perfectly with your project’s requirements. Let’s explore some common customizations you might want to consider:

1. Adding Custom Buttons

One of the most common customizations is adding custom buttons to the editor’s toolbar. This allows you to extend the editor’s functionality beyond the default options.

2. Customizing Styles and Formatting

Froala allows you to customize the available text formatting options, such as font size, font family, and text color. You can also define custom styles for your project.

3. Image and Media Handling

Integrating media handling capabilities into your inline editor can greatly enhance its usefulness. Froala supports image and media embedding, allowing users to add images, videos, and other multimedia content directly into the text.

Conclusion

Incorporating an Inline React Editor into your web application using Froala’s Inline Mode is a powerful way to enhance the user experience and provide rich text editing capabilities.

With its flexibility, customization options, and straightforward integration, Froala makes it relatively simple to create a feature-rich text editor that suits your project’s needs.

Throughout this article, we’ve covered the essential steps for setting up the Froala Inline Mode within a React application.

We’ve also explored various customization options, from adding custom buttons to handling media uploads, and discussed how to handle user-generated content.

By following these guidelines and experimenting with Froala’s extensive documentation and examples, you’ll be well on your way to implementing a seamless and user-friendly inline text editor in your React project.

Whether you’re building a CMS, a collaborative writing platform, or any application requiring rich text editing, Froala’s Inline Mode can be a valuable addition to your toolkit.

Document Ready Mode on a Froala Component in Your React App

Document Ready React editor

Rich text editors are indispensable tools for creating, editing, and formatting content.

These editors empower users to craft appealing and structured text without needing in-depth knowledge of HTML and CSS.

Froala is a tool that provides a powerful and customizable rich text editing experience, and it integrates with React applications.

One of its features is the Document Ready mode, which simplifies document view.

In this article, we’ll explore how to use the Document Ready mode of Froala in your React project app.

What is Document Ready Mode?

Document Ready React editor

Froala’s Document Ready mode is a feature that simplifies the initialization of the editor and allows you to focus on creating content rather than wrestling with configuration settings.

It streamlines the setup process, making it more straightforward and user-friendly.

Prerequisites

Before we dive into using Document Ready mode, let’s ensure you have everything in place:

React Project: You should have a React project set up. If not, you can create one using create-react-app or your preferred method.

Installation: Install Froala Editor in your React project using npm or yarn:

npm install react-froala-wysiwyg --save

Import Styles: Import Froala’s CSS styles in your project. You can do this by adding the following line no App.js file:

import "froala-editor/css/froala_style.min.css";

import "froala-editor/css/froala_editor.pkgd.min.css";

Initializing Froala Editor Component

Now that we’ve got the prerequisites out of the way, let’s initialize Froala Editor in Document Ready mode within your React project. Follow these steps:

1. Import Froala Editor

In your React component where you want to use Froala Editor, start by importing the necessary dependencies:

import FroalaEditorComponent from "react-froala-wysiwyg";

2. Create the Component

Next, create your React component with this code:

function App() {

  let model = '<p><a href="https://froala.com">Froala WYSIWYG Editor</a></p>';

  return (

    <div id="froala-editor">

          <h1>Froala WYSIWYG Editor </h1>

          <h2>Tutorial about Document Ready</h2>

      <FroalaEditorComponent

        tag="textarea"

        model={model}

        config={{

          quickInsertTags: [""],

        }}

      />

    </div>
  );
}

export default App;

In the above code, we’ve created a simple React component.

Froala rich text editor

3. Configure Froala Editor

To make the most of Froala Editor, you can configure it according to your needs.

Inside the initialization code block, you can pass configuration options as an object. Here’s an example of some common options you might want to use:

toolbarButtons: ['bold', 'italic', 'underline'],

Customized WYSIWYG Editor

In this example, we’ve customized the toolbar buttons. You can explore more configuration options in Froala’s official documentation.

Include Document Ready mode

Use this line to change your component for the Document Ready mode.

 documentReady: true

The “document ready mode” feature in the Froala WYSIWYG HTML Editor is designed to enhance the editing experience when creating online documents, making it more akin to using traditional word processors like Microsoft Word or Google Docs.

Document Ready Editor

Enabling Document Ready Mode: When you enable the document mode in the Froala editor, it automatically configures the editor with optimized settings for creating documents.

These settings are tailored to make the editor behave more like a traditional word processor, making it easier to work with documents.

In summary, the Froala WYSIWYG HTML Editor’s “document ready mode” feature simplifies creating online documents by providing a set of optimized settings and essential tools for document editing.

It bridges the gap between traditional word processors and web-based editing, ensuring that your documents can be printed or exported as PDFs with ease, just like you would in a typical word processing software.

This feature can be particularly advantageous for web applications or websites that require users to generate and manage documents online.

The component will have this code:

import "froala-editor/css/froala_style.min.css";

import "froala-editor/css/froala_editor.pkgd.min.css";

import FroalaEditorComponent from "react-froala-wysiwyg";

function App() {

  let model = '<p><a href="https://froala.com">Froala WYSIWYG Editor</a></p>';

  return (

    <div id="froala-editor">

          <h1>Froala WYSIWYG Editor </h1>

          <h2>Tutorial about Document Ready</h2>

      <FroalaEditorComponent

        tag="textarea"

        model={model}

        config={{

          documentReady: true

        }}
      />

    </div>
  );
}
export default App;

Conclusion

By following the steps outlined in this article, you can easily integrate Froala Editor into your React project app using Document Ready mode.

This approach simplifies the setup process, allowing you to focus on creating and editing rich content while taking advantage of Froala’s extensive customization options.

Remember to refer to Froala’s official documentation for a comprehensive list of configuration options, events, and advanced features.

With Froala Editor and React, you can provide your users with a seamless and intuitive rich text editing experience in your web applications. Happy editing!

Froala with Grammarly Text Editor SDK Alternative

Integrating Froala with Grammarly Text Editor SDK Alternative

Grammarly announced that it would be discontinuing the Text Editor SDK, the developer tool that puts the company’s automated editing functionality into any app. The tool will be shut down on January 10th, 2024, after which the functionality will cease to work in any applications where it’s in use.

If you use Grammarly Text Editor SDK and your business will be affected by this change. You don’t need to worry. We’ve got you covered.

A WYSIWYG Editor that can integrate with Different JavaScript tools

Froala is a powerful WYSIWYG editor that can be easily integrated with different JavaScript tools on the web. Fortunately, there are a lot of JavaScript tools that provide similar Grammarly features. Incorporating a Grammarly alternative with Froala will maintain the same user experience in your application.

For instance, if you are looking for a grammar check and spelling correction suite, you can use WProofreader, the AI-powered component of WebSpellChecker. WProofreader works with the Froala editor seamlessly, providing real-time grammar, spelling, and punctuation checks. Check out how this integration works and see a working demo on our WProofreader integration page.

Another good Grammarly alternative is Sapling. In addition to grammar checking, Sapling also offers deep learning-powered autocomplete suggestions across all messaging platforms.

How to Integrate Sapling with Froala

Integrating Froala with Sapling

Integrating Sapling with Froala is a straightforward process that requires minimal coding. Sapling offers an extensive API as well as SDKs that assist in grammar-checking text for Python and JavaScript, and an HTTP API that is language-agnostic. In this post, we will use the grammar-checking SDK for quick integration with Froala. Here are the steps required.

Prerequisites:

  • Registering for an API key:

    Sapling offers a free plan with limited capabilities but it comes with a free 30-day trial of Sapling Pro. To allow you to try Sapling capabilities. Sign up for Sapling, and get your API key, to get started.

  • Prepare your environment:

    Sapling and Froala are versatile tools that support popular JavaScript frameworks like React, Angular, and Vue. Both offer guidance on how to integrate within these frameworks. However, for the sake of clarity, this article will focus on a straightforward integration using basic HTML and JavaScript. You can then adapt these principles to your favorite framework.

Get started

At the beginning, create an HTML document with a single element where the editor will be initialized.

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Froala & Sapling</title>

</head>

<body>

    <div id="editor-element">Lets get started!</div>

</body>

</html>

Start with initializing Froala:

  • Include Froala Stylesheet on the page header
    <!-- include the latest Froala version stylesheet -->
    <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />
  • Include the Froala script before the closing </body> tag
    <!-- include the latest Froala version script -->
    <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>
  • Initialize the Froala editor by calling the Forala constructor function and passing the element selector as the first parameter
    <script> 

        new FroalaEditor('#editor-element');

    </script>

Now, if you open your HTML page on your browser, you should see the Froala editor opened

Froala editor initialized

Initializing Sapling:

  • Include the Sapling JavaScript file:
<script src="https://sapling.ai/static/js/sapling-sdk-v1.0.5.min.js"></script>
  •  We need to initialize Sapling after the editor loads. In this case, we can initialize it inside the Froala initialized event or in the callback function which is passed as the third parameter to the Froala constructor function. Basically, it is the same as doing it like this
    <script> 

        let editor = new FroalaEditor('#editor-element',{},function(){

            Sapling.init({

              key: '***',

              mode: 'dev',

            });          

        });

    </script>
  • Or doing it like this
    <script> 

        new FroalaEditor('#editor-element',{

            events: {

                'initialized': function () {                   

                Sapling.init({

                        key: '***',

                        mode: 'dev',

                        });

                }
            }

        });

   </script>

The Sapling init method takes an object that includes the following properties:

  • `key`: This is the API key you received when you signed up for Sapling.
  • `mode`: This can be either `’dev’ for development mode, or ‘prod’ for production mode. It determines what API endpoints Sapling will use.

Note:

  • During development, you can pass in the API key and use Sapling’s endpoints by setting mode: ‘dev’ in the init function.
  • For production, do not pass the API key in JavaScript. Instead, include the API key in your backend and call Sapling’s endpoints from the backend. This is the default setting with mode: ‘prod’.
  • Remember to replace ‘***’ with your Sapling API Key.

Once Sapling is initialized, we can call any of the methods mentioned in the Sapling docs.

We will use Sapling.observe to observe the editor for changes and provide grammar corrections and suggestions every time we add content.

  <script> 

    new FroalaEditor('#editor-element',{},function(){

        Sapling.init({
            key: '***',
            mode: 'dev',
        });

        // `this` is the editor instance

        const contentEditable = this.$el[0];

        Sapling.observe(contentEditable);
    });

 </script>

 The observe method’s first parameter should be the contenteditable or textarea element that needs to be observed. In our example we used the this keyword, which contains the editor instance, to get the editing area element.

Open the HTML file in your browser to test integration. Grammar checks should automatically be applied as you type in the editor. After clicking on the incorrect text, a popup displays suggested corrections. Select the desired correction to apply it to the text.

Grammar checking and correction with Froala and Sapling

The full example code is

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Froala & Sapling</title>
    <!-- include the latest Froala version stylesheet -->
    <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />
</head>
<body>

    <div id="editor-element" sapling-ignore="true">Lets get started!</div>

    <!-- include the latest Froala version script -->
    <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>
       
    <!-- include the Sapling SDK script -->
    <script src="https://sapling.ai/static/js/sapling-sdk-v1.0.5.min.js"></script>

    <script> 
    new FroalaEditor('#editor-element',{},function(){
       
        Sapling.init({
            key: '***',
            mode: 'dev',
        });

        // `this` is the editor instance
        const contentEditable = this.$el[0];
        Sapling.observe(contentEditable);
        
    });
    </script>
</body>
</html>

The example provided showcases only a glimpse of Sapling and Froala’s potential. We employed Sapling for live grammar and spelling checks within the editor. This can be further enhanced by tailoring Sapling to various editor events, leveraging different Sapling API methods, and even creating a custom Froala  plugin for implementing more Sapling features. 

Conclusion

The rolldown of Grammarly Text Editor SDK does not mark the end of automated writing assistant tools in your app. Explore the other options and choose the one that best fits your application’s needs.

Sapling offers a range of features such as grammar checking, writing suggestions, autocompletion, and more. You can easily integrate Sapling with the Froala WYSIWYG editor and provide users with a seamless writing experience. Using Sapling with Froala supports multiple languages, including, but not limited to English, German, and Spanish. 

Let’s start integrating Froala with Sapling and enjoy cleaner and free from grammatical errors writing experience. It is an essential add-on for writers, bloggers, marketers, or any users who frequently engage in content creation.

Leave a comment if you need help with the integration process or if you run into any issues.

Custom Buttons with Froala in an Angular Application

Froala Angular CUstom Buttons

In web development, Froala and Angular are well-known for being efficient and flexible. Froala is a WYSIWYG Editor with lots of features. Angular is a popular tool for building apps and works well with Froala. Together, they help developers save time and make better apps. For example, you can create custom buttons in the Froala editor, making apps more interactive.

 

In this guide, we’ll dig into custom buttons: why they’re awesome, how they simplify app building, and real-world uses.

The Power of Froala and Angular

But first, let’s chat about why mixing Froala with Angular makes such a big difference in web development.

Why Froala and Angular?

Froala’s Strengths:

Simple Setup: You can easily add Froala to different settings, including Angular.

Make It Yours: With Froala, you can customize a lot, like making your own buttons.

Lots to Offer: Froala lets you format text, add media, and more.

Angular’s Strengths:

Neat & Tidy: Angular is built in parts, so it’s easier to work with and keep clean.

Instant Updates: Changes you make in Angular show up in real-time.

More to Add: With tools like angular-froala-wysiwyg, Angular lets you do even more.

Tutorial: Creating Custom Buttons with Froala in Angular

Step 1: Installation

This step includes installing the necessary packages and including the required styles.

Install angular-froala-wysiwyg:

npm install angular-froala-wysiwyg

Add CSS styles to your index. file:

<link href="node_modules/froala-editor/css/froala_editor.pkgd.min.css" rel="stylesheet">

Optionally, install font-awesome for additional icons (either via npm or using the CDN in index.):

npm install font-awesome

Or

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-

Step 2: Integration with Angular

This step integrates the Froala WYSIWYG editor with your Angular application.

Generate a New Angular Application (skip if you already have one):

npm install -g @angular/cli
ng new my-app
cd my-app

Install angular-froala-wysiwyg:

npm install angular-froala-wysiwyg --save

Modify src/app/app.module.ts by Importing Froala Modules and Adding Them to the Imports Array:

 

import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';
@NgModule({

   ...

   imports: [FroalaEditorModule.forRoot(), FroalaViewModule.forRoot(), ... ],

   ...

})

Insert the Necessary Styles in angular.json within the styles array:

"styles": [
  "styles.css",
  "./node_modules/froala-editor/css/froala_editor.pkgd.min.css",
  "./node_modules/froala-editor/css/froala_style.min.css",
]

Update src/app/app.component. to Include the Froala Editor Directive:

<div [froalaEditor]>Hello, Froala!</div>

Run Your Angular Application:

ng serve

Setting Up Froala Editor in Your Angular App

  1. Install Froala: This step is all about getting Froala into your app.
  2. Integrate with Angular: Once installed, make sure Froala works well with your Angular project.
  3. Ready for Customization: With Froala now part of your Angular app, you can start adding special features. For example, you can create your own buttons like we mentioned.

By completing these steps, your Froala editor will be all set and ready for any custom touches you want to add.

Step 3: Adding Custom Buttons

Go to Your Component File

  • Find the Angular component where you want to add the new button in Froala.
  • This could be in a special editor component or somewhere broader like a form page.

Make Your Custom Button

  • Within the component, find the FroalaEditor object.
  • Use it to create and list your custom button.
  • Put this step in the ngOnInit section. This makes sure your button is ready when the page starts up.

Here’s the updated code snippet:

 

import { Component, OnInit } from '@angular/core';
import FroalaEditor from 'froala-editor';

@Component({
  selector: 'app-demo',
  template: `
    <div class="sample">
      <h2>Sample 11: Add Custom Button</h2>
      <div [froalaEditor]="options" [(froalaModel)]="content"></div>
    </div>
  `,
})
export class AppComponent implements OnInit {
  public content: string = '<p>Your initial content here...</p>';
  ngOnInit() {
    FroalaEditor.DefineIcon('alert', { NAME: 'info' });
    FroalaEditor.RegisterCommand('alert', {
      title: 'Hello',
      callback: () => {
        alert('Hello!', this);
      },
    });
  }

  public options: Object = {
    toolbarButtons: ['bold', 'italic', 'underline', 'paragraphFormat', 'alert'],
    // ...
  };
}

 

Setting Up Custom Buttons in Froala with Angular

  1. Add to Toolbar: Put your custom button, like ‘alert’, on the Froala editor’s toolbar list. This makes it show up there.
  2. Include in Template: Add the component with your custom button to the right Angular templates, so the Froala editor pops up where you want.

By setting it up this way inside the Angular component from the start, your custom button fits right into your app’s flow and looks like a built-in part of your design.

Now, run the application:

ng serve

You can view the whole demo here:

How Custom Buttons in Froala Impact the Real World

With custom buttons in Froala, you can do so much more than just regular tasks. They boost user experience and bring fresh features to life. Check out these practical uses:

Easy Content Checks: In systems that manage content, a button can send work straight to a boss for a quick check.

Quick Email Templates: For email marketing, a button can add ready-to-use templates instantly.

Help for Special Needs: You can make buttons that read out text, helping users who need it.

Work with Other Tools: Add buttons that link to calendars, calculators, or other tools to make the editor even better.

Share on Social Media: A button can post content directly to sites like Facebook or Twitter, perfect for bloggers.

Unpacking the Power of Custom Buttons in Development

Better User Experience: With buttons made just for them, users will find your apps more enjoyable.

Faster App Building: With tools like Froala and Angular, developers can make detailed features faster.

Easy Updates: Custom buttons mean you can add new things to your app without redoing everything.”

Conclusion

Froala and Angular help make app-building simpler and better. One fun feature is adding custom buttons, as shown in our guide. These buttons can speed up tasks and make apps user-friendly. They let developers add creative touches. New or seasoned at building apps? Using these buttons in Froala and Angular offers cool features to try out.

 

Get Froala Editor Now

Crafting a Custom Button for the Froala Editor in Vue.js

vue js custom button

Creating a custom button for the Froala Editor within a Vue.js application allows developers to extend the editor’s capabilities to match their project’s specific needs. This comprehensive guide will walk you through the process step by step.

vue js custom button main image

Prerequisites:

Basic understanding of and Vue.js.

Node.js and NPM are installed on your machine.

A fresh Vue.js project. If you don’t have one, set it up using the Vue CLI.

Step-by-Step Integration:

1. Setting up a New Vue Project (if needed):

If you don’t already have a Vue project,

npm install -g @vue/cli

vue create froala-vue-project

cd froala-vue-project

2. Install the vue-froala-wysiwyg package:

npm install vue-froala-wysiwyg --save

3. Setting up Froala in the project

Open the src/main.js file:

import 'froala-editor/js/plugins.pkgd.min.js';

import 'froala-editor/css/froala_editor.pkgd.min.css';

import { createApp } from 'vue';
import App from './App.vue';
import VueFroala from 'vue-froala-wysiwyg';

const app = createApp(App);
app.use(VueFroala);
app.mount('#app');

4. Set up the Froala component in your Vue template:

In src/App.vue:

 

<template>
  <div id="app">
    <froala :tag="'textarea'" :config="config" v-model:value="content"></froala>
  </div>
</template>

<script>
import FroalaEditor from 'froala-editor';

export default {
  name: 'App',
  data() {
    return {
      content: 'Your initial content here!',
      config: {}
    };
  }
};
</script>

5. Creating Your Custom Button:

  1. Define the Icon: Choose an SVG icon or use a predefined one. Here, we’ll use the ‘star’ icon:
  2. Register the Custom Button: Define your button’s functionality. In this example, the button will insert custom text:
    1. FroalaEditor.DefineIcon('myButton', {NAME: 'star', SVG_KEY: 'star'});
  3. Integrate the Button into the Froala Toolbar: Update the config object in your App.vue:
    1. config: {
        toolbarButtons: [['bold', 'italic', 'underline', 'myButton']]
        // ... any other configurations
      }
      

Here’s the final look of your App.Vue file

<template>
  <div id="app">
    <froala :tag="'textarea'" :config="config" v-model:value="content"></froala>
  </div>
</template>

<script>
import FroalaEditor from 'froala-editor';

export default {
  name: 'App',
  data() {
    return {
      content: 'Your initial content here!',
      config: {
        //... (you can add your initial configuration here)
        toolbarButtons: [['bold', 'italic', 'underline', 'myButton']]
      }
    };
  },
  created() {
    // Define the Icon for the Custom Button
    FroalaEditor.DefineIcon('myButton', {NAME: 'star', SVG_KEY: 'star'});

    // Register the Custom Button's action
    FroalaEditor.RegisterCommand('myButton', {
      title: 'Insert Custom Text',
      focus: true,
      undo: true,
      refreshAfterCallback: true,
      callback: function() {
        this.html.insert('Watch the magic happen🌠');
      }
    });
  }
};
</script>

6. Run and Test:

Launch your Vue.js application:

 

npm run serve

Open your browser to view the application. You should spot the Froala Editor with your custom button integrated. Clicking it will insert the pre-set text.

 

Here’s a demo of the working code:

 

Extra Content: The Seamless Integration of Froala with Vue.js 3 LTS Version

With the long-term support (LTS) version of Vue.js 3 now available, the benefits of using Froala with Vue.js have become even more pronounced. Here’s why:

1. Flexibility Meets Stability

The LTS version of Vue.js 3 offers a stable platform that receives regular maintenance and security updates. When you combine this stability with Froala’s adaptability, developers get a blend of reliability and flexibility that few combinations can offer.

2. Enhanced Performance:

Vue.js 3 has brought numerous performance improvements. One notable change is the async setup, which allows you to handle asynchronous operations directly within the setup function. Combined with Froala’s efficient rendering, this results in a smoother user experience.

 

<template>
  <froala :tag="'textarea'" :config="config" v-model:value="content"></froala>
</template>

<script>
import { ref } from 'vue';
import FroalaEditor from 'froala-editor';

export default {
  async setup() {
    const content = ref('Your initial content here!');
    const config = ref({
      //... (your initial configuration here)
    });

    // Let's say you fetch some content asynchronously for the editor.
    const fetchedContent = await fetchContentFromServer();
    content.value = fetchedContent;

    return {
      content,
      config
    };
  }
};
</script>

3. Better Composition API:

Vue.js 3 introduces the Composition API, which allows a more flexible code organization. Combined with Froala’s modular design, this results in cleaner and more maintainable code.

 

import { ref, computed } from 'vue';
import FroalaEditor from 'froala-editor';

export default {
  setup() {
    const content = ref('Your initial content here!');
    
    // Using the Composition API to create a computed property
    const wordCount = computed(() => {
      return content.value.split(' ').length;
    });

    // Define and register a custom button using Froala's methods within the Composition API
    FroalaEditor.DefineIcon('wordCountButton', {NAME: 'counter', SVG_KEY: 'counter'});
    FroalaEditor.RegisterCommand('wordCountButton', {
      title: 'Word Count',
      focus: false,
      undo: false,
      refreshAfterCallback: false,
      callback: function() {
        alert(`Current word count: ${wordCount.value}`);
      }
    });

    return {
      content,
      wordCount
    };
  }
};

4. Improved Customizability:

Vue.js 3 LTS comes with enhanced support for TypeScript. This means developers can now easily define types for their custom buttons or other editor extensions.

 

import { Ref, ref } from 'vue';
import FroalaEditor from 'froala-editor';

interface EditorConfig {
  toolbarButtons?: string[][];
  //... other configuration options
}

export default {
  setup(): { content: Ref<string>; config: Ref<EditorConfig> } {
    const content: Ref<string> = ref('Your initial content here!');
    const config: Ref<EditorConfig> = ref({
      toolbarButtons: [['bold', 'italic', 'underline', 'wordCountButton']]
      // ... other configurations
    });

    return {
      content,
      config
    };
  }
};

The code snippets provided demonstrate how effortlessly Vue.js 3 LTS and Froala Editor can integrate. Together, they offer a robust platform for developers aiming to create top-notch digital solutions.

 

Conclusion

Successfully adding a custom button for the Froala Editor within a Vue.js app enhances the user experience and demonstrates the flexibility of both Vue.js and Froala. This tutorial aimed to deliver a clear roadmap from the beginning to the end of the process, and we urge readers to explore further customizations to meet their unique demands. With tools like Vue.js and Froala, the possibilities are vast. Happy coding!

Do checkout our Vue.js documentation to learn more.

 

Download Froala Editor

Creating Custom Buttons with React and Froala Editor

React editor custom buttons

The Froala Editor is a powerful WYSIWYG (What You See Is What You Get) HTML editor that offers a wide range of features for creating and editing content. One of its standout features is the ability to enhance its functionality by creating custom buttons. In this article, we will explore how to create custom toolbar buttons using React and Froala Editor to enhance your experience in creating content. React editor custom buttons

Understanding the Integration of Froala Editor and React

Before delving into the creation of custom buttons, let’s briefly examine the integration of Froala Editor with React. Froala Editor is a text editor that offers a seamless and user-friendly interface for editing content. Integrating Froala with React involves wrapping the editor inside a React component, thereby combining the capabilities of both technologies. You can learn more about the integration between React and Froala in the documentation on our website. To get started, you need to install the necessary dependencies for your React project.

npm install react-froala-wysiwyg --save

Once installed, you can import the Froala Editor styles and the React component:

import React from 'react'; import FroalaEditorComponent from 'react-froala-wysiwyg'; import 'froala-editor/css/froala_style.min.css'; import 'froala-editor/css/froala_editor.pkgd.min.css';

Now, you can use the FroalaEditorComponent in your React component’s method:

const App = () => {   return (     <div >       <FroalaEditorComponent         tag="textarea"       />     </div>   ); }; export default App;

With this integration, you can have a basic Froala Editor running in your React application. However, the true power lies in creating customized buttons to enhance the capabilities of the editor.

Extending the Froala Editor with Custom Buttons

The toolbar of the Froala Editor is where users can find options for formatting text, adding images, links, and other elements. Creating custom toolbar buttons using React allows you to enhance this functionality and offer users additional features that are specifically designed for your application’s requirements. Froala Editor allows you to seamlessly integrate custom buttons into its toolbar, providing users with additional functionality tailored to their specific needs. To accomplish this, we will utilize the combination of React and the Froala Editor’s API. On the component file, import Froalaeditor component so we can use it to create the custom buttons

import Froalaeditor from 'froala-editor';

Then add the following code to create ‘Alert’, ‘Clear’, and ‘Insert’ buttons.

Froalaeditor.DefineIcon('alert', {NAME: 'info', SVG_KEY: 'help'});   Froalaeditor.RegisterCommand('alert', {     title: 'Hello',     focus: false,     undo: false,     refreshAfterCallback: false,     callback: function () {       alert('Hello!');     }   });   Froalaeditor.DefineIcon('clear', {NAME: 'remove', SVG_KEY: 'remove'});   Froalaeditor.RegisterCommand('clear', {     title: 'Clear HTML',     focus: false,     undo: true,     refreshAfterCallback: true,     callback: function () {       this.html.set('');       this.events.focus();     }   });   Froalaeditor.DefineIcon('insert', {NAME: 'plus', SVG_KEY: 'add'});   Froalaeditor.RegisterCommand('insert', {     title: 'Insert HTML',     focus: true,     undo: true,     refreshAfterCallback: true,     callback: function () {       this.html.insert('My New HTML');     }   });

Witnessing the Magic of Custom Buttons

With these custom buttons seamlessly integrated into the Froala Editor, users are empowered to utilize their extended functionalities. Each custom button reveals a unique aspect of improvement. Alert Button: The ‘alert’ button transforms into a messenger, delivering a JavaScript alert that displays the message “Hello!” when summoned with a click. Clear Button: The ‘clear’ button assumes the role of a content guardian, allowing users to remove the editor’s content while maintaining its focus, providing a blank canvas for new creations. Insert Button: The ‘Insert’ button emerges as a vessel of ingenuity, allowing users to infuse the editor’s canvas with the inscription “My New HTML,” enabling rapid creation. These custom buttons embody the essence of a personalized experience, guiding users towards a world of streamlined actions, driven by these customized functionalities.

The Flourish: Integrating Custom Buttons

The culmination of this customization journey occurs when these custom buttons are seamlessly integrated into the Froala Editor’s toolbar, enhancing the process of creating content. React takes center stage here, serving as the conduit for this integration.

import React from 'react'; import FroalaEditorComponent from 'react-froala-wysiwyg'; import 'froala-editor/css/froala_style.min.css'; import 'froala-editor/css/froala_editor.pkgd.min.css'; const App = () => {   return (     <div >       <FroalaEditorComponent         tag="textarea"         config={{           toolbarButtons: [['undo', 'redo' , 'bold'], ['alert', 'clear', 'insert']],         }}       />     </div>   ); }; export default App;

In the React component snippet above, the FroalaEditor component is imported and configured with the toolbarButtons prop. The toolbar is meticulously organized into two rows. The first row comprises standard buttons such as ‘undo,’ ‘redo,’ and ‘bold.’ The second row showcases the culmination of our endeavor – the custom buttons: ‘alert,’ ‘clear,’ and ‘insert.’ Below we can see images of the result of the component with the buttons that we saw in the React application. React editor custom buttons Froala editor React editor custom buttons editor custom buttons custom buttons By following these steps, you can seamlessly integrate custom toolbar buttons into the Froala Editor using React. This approach empowers you to enhance the editor’s capabilities beyond its default features and create a more customized editing experience for your users.

Conclusion

Customizing rich text editors such as Froala using React opens up a world of possibilities for creating dynamic and feature-rich content creation experiences. By integrating custom toolbar buttons, you can provide users with specialized functionality that aligns with your application’s requirements. This not only enhances user satisfaction but also showcases your development skills in delivering a seamless and intuitive editing environment. So, go ahead and explore the combination of React and Froala Editor to create the ideal content creation tool for your web application. We have included a working example below that shows the complete code we have discussed.

 

Building Interactive Web Apps with React and Froala Editor

React rich text editor

Web applications have become a part of our lives by facilitating seamless communication and collaboration.

Rich text-editing capabilities are a crucial aspect of web app development. Users expect a user-friendly and easy-to-use interface to compose and present text.

Froala Editor is a feature-rich and customizable WYSIWYG (What You See Is What You Get) editor that enables users to easily create and format content. It supports various text styles, images, videos, and tables. This article explains how to use Froala Editor in a React app for better text editing.

Building Interactive Web Apps with React and Froala Editor

Why Choose The Froala Editor

Before diving into the integration process, let’s briefly discuss why the Froala Editor stands out among other text editors. Froala Editor offers a comprehensive set of features that make it an excellent choice for developers and content creators.

  • Rich Text Editing Capabilities: The Froala Editor provides a user-friendly interface that allows users to format and style text similar to a word processor.
  • Responsive Design: The editor is designed to work seamlessly across different devices, ensuring a consistent experience for all users.
  • Cross-browser Compatibility: Froala Editor supports all major web browsers, including Chrome, Firefox, Safari, and Edge.
  • Customizable: Developers can customize the editor’s appearance and behavior to match the application’s theme and requirements.
  • Media Support: The editor supports various media types, such as images and videos, making content creation more engaging.
  • Undo/Redo Functionality: Users can easily undo or redo their actions. This provides a safety net for accidental changes.
  • Easy Integration: The Froala Editor offers straightforward integration with popular frameworks, such as React, making it an ideal choice for developers.

With these features in mind, let’s move on to the steps required to integrate Froala Editor into a React application.

Installation and Setup

Prerequisites

Before integrating Froala Editor into your React application, make sure you have Node.js and npm (Node Package Manager) installed on your system. This allows one to create a new React project and effectively manage its dependencies.

Creating a React Application

To start, open your terminal and use the following command to create a new React application:

npx create-react-app froala-editor-demo

cd froala-editor-demo

This will set up a new React project in a directory called froala-editor-demo. Next, navigate to the project directory and install Froala Editor SDK:

npm install react-froala-wysiwyg --save

Importing and Initializing Froala Editor

After installing Froala Editor SDK, you need to import it and initialize it within your React application. To do this, follow these steps:

Open App.js, and import the necessary modules:

Import the Froala Editor CSS

Import the Froala Editor CSS to ensure that the editor’s styles are applied correctly.

import 'froala-editor/css/froala_editor.pkgd.min.css';

import 'froala-editor/css/froala_style.min.css';

Import the Froala Editor Component

import FroalaEditorComponent from 'react-froala-wysiwyg';

Usage Examples

Now that we have the basic integration set up, let’s explore some usage examples of the Froala Editor within our React application.

Example 1: Basic Usage

Using the FroalaEditorComponent is as simple as rendering it in your desired location within your React application.

Inside the App Function remove everything and add the following return statement

  return (
    <div>

      <h1>Froala Editor App</h1>
      <FroalaEditorComponent tag='textarea'/>
    </div>
  );

The App.js code now looks like

// Require Editor CSS files.
import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/css/froala_editor.pkgd.min.css';

import FroalaEditorComponent from 'react-froala-wysiwyg';

function App() {

  return (
    <div>

      <h1>Froala Editor App</h1>
      <FroalaEditorComponent tag='textarea'/>
    </div>
  );
  
}

export default App;

Run the application and you will see the Froala editor rendered on the screen

React rich text editor

Example 2: Customizing the Editor

Froala Editor allows you to customize various aspects of the editor. You can add custom configurations by passing an options object during initialization.

<FroalaEditorComponent tag='textarea' config={{

        toolbarButtons: ['bold', 'italic', 'underline'],

        quickInsertTags: [''],

}}/>

In this example, we modified the toolbar buttons to include only basic formatting options.

Customized rich text editor

Conclusion

Rich text editing functionality can be easily added by creating interactive web applications with React and Froala Editor. In this article, we covered the installation, configuration, and fundamental usage examples for integrating Froala Editor into a React application. 

You can quickly enable Froala Editor’s extensive capabilities in your web application by following the installation and configuration instructions provided in this article.

Additionally, you can customize the editor to meet your individual needs thanks to its flexibility and customization options, which makes it a valuable tool for content creation, blog platforms, online editors, and many other web applications.

As you delve deeper into both technologies, you’ll discover a myriad of possibilities for building sophisticated web applications that cater to diverse user needs. So, go ahead, experiment, and create amazing interactive web apps with React and Froala Editor.

For more information, explore our React SDK documentation.

How to integrate Froala With Vue 3

Froala-Vue integration

We are pleased to announce that Froala version 4.1 has been released. This new version of Froala also provides users with an improved experience, better performance and accessibility. It also includes new features such as support for Vue.js 3.x.

Vue.js 3.0 is a popular JavaScript framework for developing highly reactive user interfaces. Froala improves application user interfaces by offering an intuitive, feature-rich WYSIWYG editor that comes with numerous styling options, image management features, in-built support for rich text editing, video embedding, SEO-friendly, and many other features. That’s why I’m excited to show you how easy it is to integrate the Froala WYSIWYG editor with a Vue 3 application.

Vue WYSIWYG Editor

Before diving in, we assume you have a working knowledge of:

  • JavaScript (including some of the newer, es2015 features)
  • Vue 3
  • How to use the terminal/command line
  • Node and npm

We will create a simple application and guide you step-by-step through this tutorial. There will be a working demo at the end of the article.

Step 1: Create a simple Vue project

Skip this step if you already have a Vue 3 project setup. If not, head over to your terminal/console.

Using your terminal, you can create a new Vue.js project with vue-create:

1.1 Install the Vue CLI

npm install -g @vue/cli

1.2 Inside the folder where you want to create your new Vue project run the Vue create command for a basic Vue project

vue create my-froala-vue-app

1.3 The terminal will prompt some configuration questions. Carefully answer them with your preferred set-up settings. I selected `Default ([Vue 3] babel, eslint)` for a simple Vue 3 project. I also picked ‘NPM‘ as the package manager to use when installing dependencies.

Create Vue APP.

Step 2: Install Vue WYSIWYG editor (the Froala Editor Package)

Step inside the project directory:

cd my-froala-vue-app

Once inside, install Froala’s Vue WYSIWYG editor by running the following command:

npm install vue-froala-wysiwyg --save
Note: 
This installs the latest Froala Vue SDK which supports Vue 3. If you are using an earlier Vue version, use the following command instead

npm install [email protected] --save

Unfortunately, this command will not install the latest version of Froala. Therefore, we recommend updating Vue and installing Froala using the first command.

Congratulations, you have successfully installed Froala in your Vue application. This means you can now use the VueFroala component in your project. To use the editor component in your application, you need to import it into main.js. Let’s see how to do that!

Step 3: Integration

3.1 Import Froala Editor in main.js

Open your main.js file and import the imperative bits for Froala Editor. Here’s what your file should include:

import { createApp } from 'vue'
import App from './App.vue'

//Import Froala Editor plugins
import 'froala-editor/js/plugins.pkgd.min.js';


// Import Froala Editor css files.
import 'froala-editor/css/froala_editor.pkgd.min.css';
import 'froala-editor/css/froala_style.min.css';


// Import Froala Editor component
import VueFroala from 'vue-froala-wysiwyg';

const app = createApp(App);          

app.use(VueFroala);
app.mount('#app');

3.2 Initializing the Editor

From within your project directory, open the src/App.vue file. By default, it makes use of a HelloWorld component:

<template>

  <img alt="Vue logo" src="./assets/logo.png">

  <HelloWorld msg="Welcome to Your Vue.js App"/>

</template>




<script>

import HelloWorld from './components/HelloWorld.vue'




export default {

  name: 'App',

  components: {

    HelloWorld

  }

}

</script>




<style>

#app {

  font-family: Avenir, Helvetica, Arial, sans-serif;

  -webkit-font-smoothing: antialiased;

  -moz-osx-font-smoothing: grayscale;

  text-align: center;

  color: #2c3e50;

  margin-top: 60px;

}

</style>

Remove the importing and declaring the HelloWorld component within the <script> tags since we will use the Froala editor component instead.

In the App component definition, add the data function that defines the component’s data properties. Inside the data function, add the following properties:

  • config: is an object that contains the editor API options
  • model: a string containing the editor’s default HTML content displayed by the editor.
<script>

export default {

  name: 'App',

  data () {

    return {

      config: {

        //documentReady: true,

        //direction: 'rtl',

        heightMin: 300,

        events: {

          initialized: function () {

            console.log('initialized')

          }

        }

      },

      model: '<i>Edit Your Content Here!</i>'

    }

  }

}

</script>

Finally, replace the HelloWorld component within the <template> tags with the editor component :

<template>

  <img alt="Vue logo" src="./assets/logo.png">

  <froala id="edit" :tag="'textarea'" :config="config" v-model:value="model"></froala>

</template>
  • :tag attribute is used to tell on which tag the editor is initialized.
  • :config attribute is used to configure the editor options
  • v-model:value Used to load editor content. This value is affected by editor HTML changes.

:config and v-model:value are using the config and model data properties we defined previously.
Note: There will be changes to the model value if you want to initialize the editor based on a, button, img, or input tags. We will cover these special tags in detail in another article since they change the editor’s interface.

Step 4: Run the project

After the integration is complete, it’s time to run your project to see the editor in action.

To start your local development server and see your application, run the following command in your terminal:

npm run serve

This command will start the development server and mounts your application at `http://localhost:8080`

You can always stop the server by using the `CTRl + C` command.

That should reveal your new Froala editor within your Vue 3 Project.

Step 5 Displaying HTML

To display content created with the Froala editor use the froalaView component.

<froalaView v-model:value="content"></froalaView>

Step 6: Customizing Your Froala’s Vue WYSIWYG editor

Customizing the Froala editor is distinctively easy. The powerful Froala Editor API allows customizations by adjusting our config object. Refer to the API options, events, and methods docs to see what it offers. For instance, you can edit toolbar buttons using the toolbarButtons API option. Here is an example

<template>

  <img alt="Vue logo" src="./assets/logo.png">

  <froala id="edit" :tag="'textarea'" :config="config" v-model:value="model"></froala>

</template>

<script>

export default {

  name: 'App',

  data () {

    return {

      config: {

          toolbarButtons: {

            'moreText': {

              'buttons': [ 'italic', 'underline', 'bold', 'strikeThrough', 'subscript', 'superscript', 'fontFamily', 'fontSize', 'textColor', 'backgroundColor', 'inlineClass', 'inlineStyle', 'clearFormatting']

            },

            'moreParagraph': {

              'buttons': ['alignLeft', 'alignCenter', 'formatOLSimple']

            },

            'moreRich': {

              'buttons': ['insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome', 'specialCharacters', 'embedly', 'insertFile', 'insertHR']

            },

            'moreMisc': {

              'buttons': ['undo', 'redo', 'fullscreen', 'print', 'getPDF', 'spellChecker', 'selectAll', 'html', 'help'],

              'align': 'right',

              'buttonsVisible': 2
            }

          },

        events: {

          initialized: function () {

            console.log('initialized')

          }

        }

      },

      model: '<i>Edit Your Content Here!</i>'

    }

  }

}

</script>

<style>

#app {

  font-family: Avenir, Helvetica, Arial, sans-serif;

  -webkit-font-smoothing: antialiased;

  -moz-osx-font-smoothing: grayscale;

  text-align: center;

  color: #2c3e50;

  margin-top: 60px;

}

</style>

Options

You can pass any existing Froala option within the config attribute. Vue SDK users will also be able to utilize a specific Froala option:

  • immediateVueModelUpdate: (default: false) This option updates the Vue model as soon as a key is released in the editor. Note that it may affect performance.

Events

As you can see in the previous example, API Events can be passed in with the options. Events are passed as an object named “events” in which you can define all the different events you want to use. Each defined event is an object where the key is the event name and the value is the callback function.

Methods

Using the editor instance from the arguments of the event callback you can call any method described in the method docs.

Custom Buttons

Furthermore, you can extend editor functionality by defining custom buttons. Froala allows us to define and add new buttons to the toolbar very conveniently and we will describe how to do this in a separate article.

Ready to build more with Froala and its Vue WYSIWYG Editor?

Froala doesn’t just provide a WYSIWYG editor but a powerful tool that enhances the user experience and makes content creation a breeze. With support for Vue, you can integrate Froala into various Vue projects ensuring a consistent user experience.

From the way you configure it, to the way you handle events or even create custom functionality, Froala’s Vue WYSIWYG Editor is remarkably simple and efficient.

Remember that an effective user interface yields better user engagement. Use Froala’s Vue WYSIWYG Editor for your content creation and enjoy the difference it makes.

Test Froala’s Vue Wysiwyg Editor

We built a Vue demo application showcasing the editor’s capabilities. You can use this as a starting point to test and understand how it works and fits your project requirements. Play with our demo and share your feedback in the comments.

 

TypeScript and Froala: The Basics

Typescript featured image

Froala Editor, renowned for its user-friendly interface and powerful features, just upped its game by introducing TypeScript support. If you’re a developer, TypeScript integration makes your life easier when working with Froala. How? Read on.

The Power of TypeScript

TypeScript, a statically typed superset of JavaScript, offers robust type-checking during development. This means errors are caught at compile-time rather than at runtime, resulting in fewer bugs and a more predictable development process. With the Froala Editor integrating TypeScript support, developers can harness these benefits when crafting rich text editing experiences.

typescript blog main image

An Illustrative Example with Froala’s tableEditButtons Option

Consider you want to initiate the Froala Editor with the tableEditButtons option. Using the newly provided TypeScript definitions, we can define our options like this:

 

export class AppComponent {
  title = 'my-app';
  public options: Partial<FroalaEditor.FroalaOptions> = {
    tableEditButtons: ['tableRows', 'tableColumns', 'tableCells', 'tableCellVerticalAlign', 'tableRemove']
  };
}

This simple code showcases two of TypeScript’s powerful features:

Autocomplete: As you start typing “tableEdit…“, your IDE will suggest available options from FroalaOptions, ensuring you pick the correct option without constantly referring to the documentation.

tableedit autocomplete

Type Checking: If you accidentally set tableEditButtons to a non-array or a boolean, TypeScript will raise a compile-time error. This immediate feedback loop is invaluable, ensuring you’re always working with valid configurations.

TypeScript error

Here’s the exact same configuration via JavaScript:

Javascript/TypeScript example

You’ll see that there’s no runtime error whatsoever. This is just a surface level explanation of the power of TypeScript with Froala.

Correct type:

TypeScript correct example

 

Going Technical: Understanding the Partial Utility Type

The use of Partial<FroalaEditor.FroalaOptions> might raise eyebrows if you’re new to TypeScript. Let’s dissect it:

Partial: A built-in TypeScript utility type, it creates a type where all properties are optional. This is immensely helpful when working with large option objects like FroalaOptions, where you might only want to specify a few settings.

FroalaEditor.FroalaOptions: This refers to the type definition provided by Froala for all available editor options. By combining it with Partial, we’re signaling that our options object will only use a subset of all available Froala options.

 

TypeScript vs JavaScript

TypeScript vs. JavaScript: Advancing with Froala

When you choose to implement a rich-text editor like Froala in your application, every decision you make can impact development velocity, bug frequency, and maintainability. One such pivotal decision is whether to use TypeScript or stick with plain JavaScript. Here’s a detailed comparison:

1. Type Safety

JavaScript: 

Being a dynamically typed language, JavaScript doesn’t allow you to define the type of a variable, leading to potential runtime errors. When working with a comprehensive library like Froala, this can cause unexpected behavior if you mistakenly assign incorrect types to editor options or misinterpret returned types.

TypeScript:

Statically Typed: At its core, TypeScript is a statically typed superset of JavaScript. This means you declare the type of variables, function parameters, and return types.

let myOption: boolean = true;

With Froala, this ensures that you’re assigning the correct types to each editor option and correctly interpreting returned values.

Compile-Time Checks: Before the code even runs, TypeScript will identify and flag type-related errors. This means if you’ve wrongly assigned a string to an option that expects a boolean, the error is caught during development rather than at runtime.

2. Autocomplete and Intellisense

JavaScript: While modern IDEs provide some level of autocomplete for JavaScript, the lack of type information can make suggestions less accurate, especially for large libraries like Froala.

TypeScript:

The enhanced type system in TypeScript allows IDEs to offer precise and context-aware autocomplete suggestions. When you’re working with Froala, as you start typing an option, the IDE will display a list of valid properties, complete with type information and even brief documentation.

This leads to faster development, less reliance on constantly referencing the official docs, and fewer mistakes.

For example, if you want to use Codox.io options you can just type “codox…” and it will show the relevant options.

codox options

3. Interface Implementation

JavaScript: Without formal interfaces, ensuring an object conforms to a specific shape or requirement in JavaScript requires manual checks and can be error-prone.

TypeScript:

Interfaces: TypeScript allows you to define interfaces, ensuring an object matches a specific structure.

 

interface FroalaCustomOption {

  theme: string;

  plugins: string[];

}

 

When using Froala, if the library offers a predefined interface for its configuration options, you can guarantee that your configuration object adheres to this structure, preventing potential errors. To learn more about TypeScript interfaces, you can check out their official guide.

4. Scalability and Maintenance

JavaScript: Larger projects can become hard to manage and maintain due to JavaScript’s dynamic nature.

TypeScript:

Offers enhanced readability and self-documenting features via its type system. In the context of Froala, as your application grows and you incorporate more features of the editor, TypeScript ensures that older integrations remain consistent and bug-free.

Refactoring becomes safer, as changes can be made with the confidence that any breaking alterations will be flagged by the compiler.

Froala, TypeScript, and Angular: Your Superpower

Angular, one of the most widely-used frameworks for building web applications, has championed TypeScript since its second version. When we intertwine the benefits of TypeScript with Froala within an Angular environment, the synergies elevate web development to new heights. Here’s why:

Native Support for TypeScript

Angular’s Foundation: Angular is built with TypeScript. This means that all of its core libraries, modules, and tooling are optimized for TypeScript. When you use Froala with TypeScript in an Angular project, you’re aligning with the natural rhythm of the framework.

Consistency: Incorporating Froala’s TypeScript features within an Angular application ensures a seamless development experience. Your Froala configurations and interactions will follow the same type patterns as the rest of your Angular components and services.

Enhanced Dependency Injection

Angular’s robust dependency injection system, combined with TypeScript’s type system, allows for more precise token retrieval. When integrating services or utilities related to Froala, TypeScript ensures you’re injecting the right dependencies.

Support for LTS version of Angular

Froala supports the latest version of Angular’s SDK. You can read more about it here.

Conclusion

TypeScript’s integration into the Froala Editor ecosystem isn’t just a flashy addition; it’s a game-changer. With powerful features like autocomplete and compile-time type checking, developers can work faster, smarter, and with greater confidence.

Are you ready to supercharge your Froala Editor experience with TypeScript? Dive in today and experience the difference!

Download Froala Editor

 

 

 

 

Integrate Froala with React

integrate Froala with React

Earlier this week, Froala announced its most impressive editor release ever 4.1. This release was eagerly anticipated by React developers since it supports React 18. This means you can now easily include a React WYSIWYG editor component in your React application made using Froala, the top WYSIWYG editor.

Froala provides a modern user interface React WYSIWYG editor equipped with hundreds of features including a powerful API, basic and advanced rich text editing functions, SEO-friendly content, accessibility support, security, and compatibility with MS Word, Excel, and Google documents.

In this article, we will demonstrate how to initialize Froala’s editor in a React application using Froala’s React SDK.

We assume you have a working knowledge of:

  • JavaScript (including some of the newer, es2015 features)
  • React
  • How to use the terminal/command line
  • Node and npm

We will create a simple application and guide you step-by-step through this tutorial. There will be a working demo at the end of the article.

React WYSIWYG editor

Step 1: Creating A React App.

Skip this step if you will install the editor in an existing React app.

  1. Open the Node.js command prompt
  2. Navigate to the location where you want to install the React app.
  3. Since we don’t have a running React app. we will create a new React application using a package called create-react-app. To install the package run
    npm install -g create-react-app
    Note:
    If you’ve previously installed create-react-app it globally via npm install -g create-react-app, we recommend uninstalling the package using npm uninstall -g create-react-app or yarn global remove create-react-app. Then install it again to ensure that npx always uses the latest version.
  4. Run:
    npx create-react-app my-froala-editor-app

    A command which creates a React app. Create React app

    After running this command, if you go to the specific location you will find a folder called my-froala-editor-app containing the React app files.

Step2: Installing Froala

Navigate to the my-froala-editor-app folder via your terminal/command line window.

cd my-froala-editor-app

Once inside, install Froala’s React SDK by running the following command:

npm install react-froala-wysiwyg --save

Don’t forget, the --save flag is important as it adds the installed NPM package to the dependencies in your package.json file. This ensures that the Froala editor is included in your deployed application.

install Froala react SDK

Check your application’s node_modules directory or the package.json file for a successful installation of the Froala library. The react-froala-wysiwyg should now be present

Step3: Displaying the Froala Editor

Once you have installed the Froala React SDK, you can display the editor in any existing component by nesting <FroalaEditorComponent tag='textarea'/> into it.

As a test, open the app.js file in the src folder and edit it as follows:

    1. First, import the editor CSS stylesheet so the editor UI appears correctly
      // Require Editor CSS files.
      import 'froala-editor/css/froala_style.min.css';
      import 'froala-editor/css/froala_editor.pkgd.min.css';

      Note:
      froala_style.min.css: Only needed if you display the editor content outside the rich text editor to preserve the look of the edited HTML.
      froala_editor.pkgd.min.css: Contains the editor UI styles, such as the toolbar, buttons, popups, etc.

    2. Import FroalaEditorComponent so you can use the component inside the app function
      import FroalaEditorComponent from 'react-froala-wysiwyg';
    3. Place a <FroalaEditorComponent tag='textarea'/> where you want the editor to appear. I will add it under the <header> element. The app.js should now look like this
      import logo from './logo.svg';
      
      import './App.css';
      
      import 'froala-editor/css/froala_style.min.css';
      
      import 'froala-editor/css/froala_editor.pkgd.min.css';
      
      import FroalaEditorComponent from 'react-froala-wysiwyg';
      
      function App() {
      
      return (
      
      <div className="App">
      
      <header className="App-header">
      
      <img src={logo} className="App-logo" alt="logo" />
      
      <p>
      
      Edit <code>src/App.js</code> and save to reload.
      
      </p>
      
      <a
      
      className="App-link"
      
      href="https://reactjs.org"
      
      target="_blank"
      
      rel="noopener noreferrer"
      
      >
      
      Learn React
      
      </a>
      
      </header>
      
      <FroalaEditorComponent tag='textarea'/>
      
      </div>
      
      );
      
      }
      
      export default App;
    4. That’s it, run the app using the command npm start
    5. The http://localhost:3000 should be open automatically on your browser and that app now is running. Scroll down and you will find the Froala editor displayed with its basic configuration under the default React header

Step4: Create a custom Froala Editor component

As you can see it is very simple to install and use the Froala editor inside your application. However, since most developers will need to customize the editor function and style to their needs before displaying it, let’s see how we can do this.

Ideally, you will need to create a custom React component. Component files are where you define the structure, the UI logic, and the component’s specific behaviors, including state handling and methods that get executed in response to user actions.

React supports two types of components:

  1. Class component
  2. Functional component

There are a few fundamental differences between the class and functional components:

  1. Syntax: Class components are written as ES6 classes, while functional components are simple JavaScript functions.
  2. Lifecycle Methods: Class components allow you to use lifecycle methods (like componentDidMount, componentDidUpdate, and componentWillUnmount). Prior to React 16.8, functional components did not have this ability. However, with the introduction of Hooks in React 16.8, you can now use features like state and lifecycle methods in functional components using useEffect.
  3. State Management: Before React 16.8, state could only be used in class components. Now, however, with the introduction of the useState and useReducer hooks, you can use state in functional components too.
  4. This Keyword: In class components, the this keyword is used to access props, state, and methods. In functional components, there’s no this keyword, and props are passed in as a function argument.
  5. Boilerplate & Readability: Class components often require more code than functional components. And due to the simplicity of functional components, especially with hooks, they can lead to more readable code for some developers.

Froala SDK can be used in both types as declared in the SDK documentation. In this article, we will use the functional component.

Create a new directory in the src directory called components and create a file called FroalaBasicEditorComponent.jsx in that directory. Feel free to use a different name but remember to write it correctly in the code.

folder stracture

Similar to what we did in the App.js we will import the editor styles, and the editor component and call it inside whatever HTML markup we want. The EditorComponent.jsx now should be like

import React from 'react';

// Require Editor CSS files.

import 'froala-editor/css/froala_style.min.css';

import 'froala-editor/css/froala_editor.pkgd.min.css';

import FroalaEditorComponent from 'react-froala-wysiwyg';

// Render Froala Editor component.

function EditorComponent (){

return (

<div class="editor">

<h3> Froala's React WYSIWYG Editor</h3>

<FroalaEditorComponent tag='textarea'/>

</div>

);

}

export default EditorComponent;

As you can see, we simply return a header and put FroalaEditorComponent inside a div with class editor. Finally, we export the new component so we can import it into other components.

Now we can remove the lines we added previously to the App.js file and add the following:

import EditorComponent from './components/EditorComponent';

and <EditorComponent /> replaces <FroalaEditorComponent tag='textarea'/> so App.js should look like this:

import logo from './logo.svg';

import './App.css';

import EditorComponent from './components/EditorComponent';

function App() {

return (

<div className="App">

<header className="App-header">

<img src={logo} className="App-logo" alt="logo" />

<p>

Edit <code>src/App.js</code> and save to reload.

</p>

<a

className="App-link"

href="https://reactjs.org"

target="_blank"

rel="noopener noreferrer"

>

Learn React

</a>

</header>

<EditorComponent />

</div>

);

}

export default App;

and if you open http://localhost:3000 you will see it display the same page layout as it is. Now we will customize the EditorComponent.jsx to customize the editor.

Let’s create a custom stylesheet file called EditorComponent.css where we can style the HTML elements related to the component. For example, centering the “.editor” div

.editor{

width: 60%;

margin: 60px auto;

}

We should then import that CSS file inside the EditorComponent.jsx like this

import './EditorComponent.css';

Basic Froala React editor

Now let’s customize the editor to load all plugins:

To load the full-featured editor, simply import the plugins JS file

// Import all Froala Editor plugins;
import 'froala-editor/js/plugins.pkgd.min.js';

Now the editor turns out to be like this

full-featured React editor

More customizations

The Froala editor has a powerful API with more than a hundred options, events, and methods. For example, you can use the API options to turn the editor into a document editor. Easily pass the desired options in the config object while calling the FroalaEditorComponent in your component.

function EditorComponent (){

    let config = {
      documentReady: true,
      heightMin: 300,
      events : {
        'contentChanged' : function(e, editor) {
          console.log('test');
        }
      }
    };

  return (
    
      <div class="editor">
        <h2> Froala's React WYSIWYG Editor</h2>
       <FroalaEditorComponent tag='textarea' config={config} />
      </div>
  );

}

export default EditorComponent;

Similarly, the events are also passed through the config object. For example:

function EditorComponent (){

    let config = {
      documentReady: true,
      heightMin: 300,
      events : {
        'contentChanged' : function(e, editor) {
          console.log('test');
        }
      }
    };

  return (
    
      <div class="editor">
        <h2> Froala's React WYSIWYG Editor</h2>
       <FroalaEditorComponent tag='textarea' config={config} />
      </div>
  );

}

export default EditorComponent;

There is a lot you can do with Froala, such as changing the default language, changing the editor theme, adding a custom button, and loading a special component. Later, we will have dedicated articles about this.

For now, have fun with Froala’s React WYSIWYG editor demo.

Froala Blog Call To Action

Enhance Your React Forms With a Rich Text Editor

react rich text editor
React, a popular JavaScript library for building user interfaces, offers a seamless development experience.  The 2023 StackOverFlow survey with 60,000 developers highlights that React remains one of the most popular frameworks and web technologies used by professionals. However, when it comes to forms, React’s native input components cannot handle rich text formatting.  In content creation, blog posts, or email composition scenarios, users need formatting options like bold, italic, bullet points, and hyperlinks. 

Improving the experience

Integrating a rich text editor is essential to overcome this limitation and provide a robust form experience.  By incorporating a rich text editor, developers can empower users to express themselves more effectively and enhance their experience. This article will explore how to enhance React forms using Froala Editor, a customizable rich text editor solution. 

Creating a Project

If you haven’t already, set up a new React project by running a Create App React:
npx create-react-app my-app
Before installing the Froala package, enter the newly created app directory with the command.
cd my-app
Install the Froala Editor package in your React project.  This package provides components and stylesheets required for integrating Froala Editor seamlessly into the application. You can do this by running the following command in your project directory. 
npm install react-froala-wysiwyg 

Starting the code

Import Froala Editor: In the component where you want to use the rich text editor, import the elements from the Froala Editor package.
import ‘froala-editor/css/froala_editor.pkgd.min.css’; import ‘froala-editor/css/froala_style.min.css’; import FroalaEditor from ‘react-froala-wysiwyg’; import React from ‘react’;
Implement the Editor: In your component’s render method, add the FroalaEditor component, passing the necessary props. 
  class ReactForm extends React.Component {     constructor(props) {       super(props);       this.state = {         editorContent: ,       };     }
The code is defining a class called ReactForm which extends React.Component class. This indicates that ReactForm is a component in a React application. The constructor method is used to initialize the state of the component. In React, a state is an object that holds the data that can change over time and affect the component’s rendering. The constructor takes in a props parameter, representing the properties passed to the component. Inside the constructor, the super(props) statement is called, which is necessary when defining a constructor in a subclass of React.Component. It calls the constructor of the parent class (React.Component), passing in the props parameter. This ensures that the component is initialized correctly according to the React.Component implementation. The state property of the component is set using this.state = { editorContent: ” }. Here, editorContent is the key in the state object, and its initial value is an empty string (”). The state object is used to store and manage the data specific to the component.
    handleEditorChange = (content) => {       this.setState({ editorContent: content });     }
This code defines an arrow function called handleEditorChange within the class ReactForm. This function takes a parameter called content. The function is used as an event handler for updating the state of the component. In particular, it is designed to handle changes in an editor, where the content parameter represents the updated content of the editor. Inside the function body, this.setState({ editorContent: content }) is called. setState is a method provided by the React.Component class that allows you to update the state of a component. In this case, setState is called with an object { editorContent: content }. This object specifies the new state values to be updated. Using setState, React knows that the state has changed, and it triggers a re-render of the component, causing any parts of the UI that depend on the state to update accordingly.
    render() { return ( <div> <h2>React Form</h2> <FroalaEditor tag=’textarea’ onModelChange={this.handleEditorChange} config={{ toolbarButtons: [‘bold’, ‘italic’, ‘underline’], }} /> </div> ); } } export default ReactForm;
The code shows the render method of the ReactForm component. In React, the render method is responsible for generating the JSX (JavaScript XML) that represents the component’s UI. Inside the render method, there is a return statement that wraps the JSX within parentheses. The returned JSX represents the structure and content of the component’s UI. In this case, the returned JSX consists of a <div> element as the root container. Within the <div>, there is an <h2> element with the text “React Form” as the heading. Below the <h2> element, there is a FroalaEditor component. It is assumed that the FroalaEditor component is imported from an external library or component module. The FroalaEditor component represents an editor component for handling text input. The FroalaEditor component has several props passed to it: tag=’textarea’: This prop sets the underlying HTML tag of the editor component to be a <textarea>. It indicates that the editor should behave as a textarea input field. onModelChange={this.handleEditorChange}: This prop sets the event handler function handleEditorChange to be called whenever the content of the editor changes. It means that whenever the user makes changes to the editor’s content, the handleEditorChange function will be invoked. config: This prop is an object that contains configuration options for the editor component. In this case, the toolbarButtons option is set to an array [‘bold’, ‘italic’, ‘underline’]. This configures the toolbar buttons of the editor to only display the buttons for bold, italic, and underline formatting options. Overall, the render method generates the JSX that represents the UI of the ReactForm component. It includes a heading, a FroalaEditor component for text input, and sets the event handler and configuration options for the editor. The complete component will be this:
import ‘froala-editor/css/froala_editor.pkgd.min.css’; import ‘froala-editor/css/froala_style.min.css’; import FroalaEditor from ‘react-froala-wysiwyg’; import React from ‘react’; class ReactForm extends React.Component {     constructor(props) {       super(props);       this.state = {         editorContent: ,       };     }        handleEditorChange = (content) => {       this.setState({ editorContent: content });     }        render() {       return (         <div>           <h2>React Form</h2>           <FroalaEditor             tag=‘textarea’             onModelChange={this.handleEditorChange}             config={{               toolbarButtons: [‘bold’, ‘italic’, ‘underline’],             }}           />         </div>       );     }   }   export default ReactForm;
In this example, we limit the toolbar buttons to include bold, italic, and underlined options. You can explore the Froala Editor documentation to discover the available toolbar buttons and their corresponding names. That’s it! You now have a rich text editor integrated into your React form using Froala. 

Formatting options

Users can input and format text content with formatting options provided by the editor. Integrating a rich text editor into React forms empowers developers to offer users a powerful and intuitive content creation experience.  By providing a range of formatting features, Froala Editor enhances the functionality of React forms, enabling users to create visually appealing and well-structured content effortlessly.  Integrating a rich text editor into React forms is a game-changer for capturing and manipulating rich text content.  React forms become more versatile and user-friendly, allowing users to format text, insert media, and customize their content.  Froala Editor provides a solution for seamlessly integrating a feature-rich text editor into React applications.  Its extensive customization options and plugin support allow developers to create highly tailored and engaging editing experiences. Download Froala Editor

Rank Higher on Google in 2024 with the SEO-friendly editor

SEO optimized content

With thousands of websites in your niche, how can you be the first result on Google for a certain keyword? If you don’t plan to spend a lot of money on paid ads, you have to optimize your web pages for search engines. Search engine optimization (SEO) is very important as it has many benefits from increasing organic traffic to boosting your site’s credibility.

SEO tips

SEO rules are updated quickly and you should learn the latest techniques to stay ahead of your competitors. However, there are some rules that are mandatory to be applied on every page and post you publish.

In this article, you will learn six essential on-page SEO tips to help your website rank higher on Google and other search engines. We will also explain how to incorporate these tips into your content using the SEO-friendly WYSIWYG editor Froala, which is much more convenient than manually modifying your HTML code, especially if you have no HTML programming skills.

 

How Froala can help you create a SEO-friendly content

Froala is easy to integrate with any web application using a few lines of code. It supports many web development frameworks. If you are using WordPress, download the WP plugin to get started. Alternatively, download the editor files to get started using it in any HTML/Javascript environment.

You can also use it online on this free online HTML editor tool, by copying your HTML into the editor, editing it, and copying it again into your application.

The advantage of using Froala to edit your content instead of editing the HTML content manually is the ability to see exactly how the content will look to the end users. Moreover, you can edit the HTML tags through Froala intuitive popups without the need to know these tags. This enables fast editing of the page content and accurately generated output without the need to learn HTML.

Now, let us start with the six powerful on-page SEO tips that will help you rank higher and boost your website’s organic traffic.

How to Optimize Your Content with Froala

1. Optimize Your Meta-Tags

Meta-tags play a crucial role in influencing click-through rates and rankings.

  • Title Tags: Keep them under 60 characters, incorporate primary keywords, and reflect the content’s topic
  • Meta Descriptions: Limit to 155 characters, include relevant keywords and create a compelling description of the page’s content
Editor configuration

Meta title and meta tags go under the <head> tag of your HTML. Most of the WYSIWYG editors strip out the <head> tag and its content, allowing you to only edit the page content. Froala also does this by default but you can change this behavior easily by setting the fullPage API option to true

new FroalaEditor('.selector', {

  fullPage: true

});

Then, you will be able to edit your whole HTML document, including the head section, where you can add and update your meta-tags effectively.

How to optimize Meta-tags using Froala:

Click on “More Misc” toolbar button then click on “Code View” button then start editing the meta tags. after finish editing click on the “Code View” button again to switch back to rich text editing mode.

2. Optimize Headings

Ensure that your headings accurately reflect the content to provide a better user experience. Use header tags (H1, H2, and H3) for a well-organized and structured page that search engines can easily crawl.

  • Utilize H1 tags for the main heading of the page, typically the title. Ensure only one h1 on a page.
  • Use H2 and H3 tags for subheadings, ensuring good organization and logical flow
  • Include targeted keywords in your headings, but don’t overdo it
Editor configuration

In Froala, you can quickly format headings using the toolbar options or keyboard shortcuts. By default, the paragraph format dropdown allows you to format the selected text in one of the below formats:

  • Heading 1: will wrap the selected text in <h1> tag.
  • Heading 2: will wrap the selected text in <h2> tag.
  • Heading 3: will wrap the selected text in <h3> tag.
  • Heading 4: will wrap the selected text in <h4> tag.
  • Code: will wrap the selected text in <pre> tag.
  • Normal: will warp text in <p> or <div> based on the value of the enter API option

The enter API option allows you to determine which tag <p>, <div>, or <br> to be inserted when the ENTER key is hit. Making the “Normal” paragraph option dependent on the “enter“ API option value is a great way to provide consistency in the produced HTML code which is also great for SEO.

If you want to add another paragraph format to the editor dropdown, you can easily edit the available options through the `paragraphFormat` API option. it is an object whose key is the HTML tag and its value is the text that will be displayed on the dropdown menu. For example, if you added into it the following code

paragraphFormat: {

SECTION: 'Block'

}

then in the dropdown menu, you will find the text “Block“, that when you select it, the paragraph code will turn into

<section>paragraph </section>

Use paragraph format options to ensure a clean and consistent HTML structure that is SEO-friendly.

new FroalaEditor('.selector', {
  paragraphFormat: {
    N: 'Normal',
    H1: 'Heading 1',
    H2: 'Heading 2'
  }
});

How to optimize headings using Froala:
  • Select the text
  • Click on “More Paragraph” button
  • Click on “Paragraph Format” button
  • Select the desired format

3. Add Alt Text to Images

Optimize the images by adding descriptive image alternative text (ALT), and captions to make them crawlable and accessible to visually impaired users.

The Froala image editing popup is giving you the ability to optimize your visuals for SEO without any hassle. Moreover, You can change the displayed image size, insert a link, and many more. you can control which options are displayed on this popup by editing the imageEditButtons API option. Furthermore, if you need to add custom functionality, you can create a Froala custom button and add it to the image editing popup through that option.

  • Alt text

Search engines cannot interpret images, so adding image alternative text (ALT) is essential for indexing and ranking.

  • Describe the image accurately while keeping the description concise
  • Include relevant keywords to improve the picture’s ranking
How to edit Alt text using Froala:
  • Click on the image
  • Click on the “alternative text” button from the popup that appears
  • Enter your alt text
  • click “Update“
  • Caption

Adding captions to your images can provide additional context and improve user engagement. Captions should be brief and informative.

  • Use concise and relevant descriptions for your captions
  • Include targeted keywords whenever appropriate, without overusing them
How to add image captions using Froala:
  • Click on the image
  • Click on “Image Caption” button from the popup that appears
  • Type in your desired caption and it will appear below the image.

SEO friendly editor

 

4. Utilize Internal and External Links

Linking to other relevant pages within your website (internal links) and to authoritative sources (external links) can improve SEO and user experience. This practice creates a better user experience, defines your website’s structure, and provides reference sources for your content. To optimize your links

  • Use descriptive anchor text for internal and external links that accurately describe the linked content.
  • Link to reputable and authoritative external sources to provide additional value and credibility to your content.
  • Regularly check and update the links to ensure they are not broken or outdated.
How to add/edit links using Froala:

In the Froala Editor, adding internal and external links is very intuitive. Simply highlight the desired text, click on the “Insert Link” option in the toolbar, enter the URL, and set the target attributes (e.g., open in a new tab).

Editing links is very easy too, just click on the link and select the edit button from the popup, then update the URL and target attributes as needed.

Editor configuration for editing link attributes

However Froala doesn’t provide editing links attributes by default, but you can customize this using the linkAttributes Froala API option.

Link ‘title’

One of the most important link attributes in SEO is link titles as they provide additional context for search engines to understand the linked content. Adding relevant and descriptive titles can improve your search engine ranking. Keep your title links short and concise but also keep them descriptive and keyword-rich.

By adding thetitle: 'Enter Title'to the linkAttributes object, a field for entering the link title will appear when adding or editing a link, allowing you to seamlessly incorporate optimized link titles into your content.

You can add more attributes to this object. The object key is the attribute name and its value is the placeholder for the created field.

Link ‘rel’

Another important attribute is the ‘rel’ attribute as it enables you to define the relationship between the linked page and your current page. For example, using rel="nofollow" can advise search engines not to follow certain links for ranking purposes. Froala linkAlwaysNoFollow option Specifies if the rel="nofollow" attribute should be added to all links.

Adding, editing, and optimizing links in Froala Editor is simple and efficient. With the right techniques, you can improve your website’s SEO, user experience, and overall performance.

5. Optimize Your Videos

Videos are engaging and can keep users on your site for a longer duration, but they also need to be optimized for SEO. Make sure your embedded videos have an SEO-friendly format, accurate title, and descriptive text.

  • Choose a suitable video hosting platform like YouTube or Vimeo for better load times and easier embedding.
  • Create accurate and engaging titles and descriptions for your videos, incorporating relevant keywords.
  • Add transcripts or captions to make the videos accessible to a wider audience and search engines.
  • Use a video schema markup to provide additional information about the video and improve search visibility.

The Froala rich text editor automatically parses YouTube, Vimeo, Yahoo, and Dailymotion video links. For videos from other sources, you can insert them by pasting the embedded code. With Froala you can also customize the video size and alignment without touching the code.

6. Quality Content is King

Creating informative, engaging, and original content is key to ranking high in search engines. The readability of your content plays a significant role in user engagement and search engine rankings. Properly formatting your text ensures it is easy to read and understand, ultimately improving the user experience and SEO performance. Ensure your content is:

  • Well-structured with headings, lists, and short paragraphs
  • Tailored to your target audience’s preferences and pain points
  • Updated regularly to maintain relevancy and add fresh insights – Free of spelling and grammatical errors for an improved user experience and better SEO results
  • Enhanced with relevant images, videos, and multimedia to engage users and support your content

The Froala Editor offers all the essential tools and formatting options for creating high-quality content, including various header styles, list types, text alignments, and media options. Remember to always proofread and revise your work to optimize your content for both users and search engines. You can integrate Froala with WProofreader spelling and grammar checker to automatically proofread the content for you.

Using On-Page SEO to Boost Page Rankings and Drive Traffic

on-page SEO plays a significant role in helping your website rank higher on search engines like Google. By implementing these six powerful SEO tips – optimizing meta-tags, headings, images, links, videos, and creating quality content – you can greatly improve your site’s visibility and organic traffic. To make this process even easier, use Froala WYSIWYG editor for an SEO-friendly editing experience. Experience Froala for free now.

Download Froala Editor

 

A Pro’s Guide to Froala’s Word and Excel Pasting

Froala Pasting plugin

Need an easy way to send Word and Excel content in your forms or messaging apps? Want to create an app compatible with Word and Excel?

Froala WYSIWYG editor is an easy yet powerful solution for reaching your goals.

 

 

Froala Pasting pluginWhy should you consider Froala for online document editor applications?

Froala will save your time and effort by providing an easy and intuitive way to implement your online document application. To make the Froala WYSIWYG editor user interface look like an online documents editor, you simply need to set the documentReady Froala API option to true. By doing this:

  • Froala will display only the most frequently used toolbar buttons for editing documents.
  • Froala reorder toolbar buttons to provide the best document editing experience.
  • The editing area’s default height will be increased to resemble a typical A4 document.

If you don’t like the defaults, With Froala editor, you can change the theme, add more toolbar buttons, customize the buttons’ order, and extend functionality with custom plugins.

Is Froala editor compatible with Word and Excel?

Froala editor is compatible with Microsoft Word documents and Excel sheets. This enables the smooth transfer of content, retaining the same format, between these applications. This is made possible by Froala’s enhanced Microsoft Word and Excel Pasting Plugin, also called the Word Paste plugin.

Word content contained an excessive amount of unnecessary markup, making implementation of this feature challenging. Moreover, important information that doesn’t come as HTML has to be parsed and converted appropriately for the browser to render it.

As a leading WYSIWYG editor, the Froala team accepted this challenge and worked hard to support Word markup. Furthermore, when Word images are pasted into the editor, we process them and upload them to your server in the same way as regular images.

In our comparisons with other WYSIWYG editors such as TinyMCE and CKEditor, we found that Froala preserved the original formatting of the content pasted from Microsoft Word and Excel better than any other editor.

Configuring Froala’s Enhanced Microsoft Word and Excel Pasting Plugin

With Froala’s Enhanced Microsoft Word and Excel Pasting Plugin, copying and pasting content from Microsoft Word or Excel into a WYSIWYG editor is easy and streamlined. It includes several options and events for customizing it to best suit your application. Let’s explore its configurations further.

Options

wordPasteModal

Set whether you want to display a modal to choose if you want to keep the pasted style or not.

wordPasteKeepFormatting

If you choose to not display the modal, you can specify here whether the editor will keep the pasted styles or not. By default, the editor will keep the styles.

wordDeniedTags

An array of HTML tags that will be removed altogether with their content when pasting content into the rich text editor from Word. For example, to remove links from the pasted content set this option to

new FroalaEditor('.selector', {

wordDeniedTags: ['a']

});

wordDeniedAttrs

An array of HTML attributes to be removed altogether with their content when pasting content into the rich text editor from Word. For example, to remove the id of the pasted elements set this option as

new FroalaEditor('.selector', {

wordDeniedAttrs: ['id']

});

wordAllowedStyleProps:

An array contains the allowed CSS properties to be used for tags when pasting from Word. by default it is set to allow the following properties

['font-family', 'font-size', 'background', 'color', 'width', 'text-align', 'vertical-align', 'background-color', 'padding', 'margin', 'height', 'margin-top', 'margin-left', 'margin-right', 'margin-bottom', 'text-decoration', 'font-weight', 'font-style', 'text-indent', 'border', 'border-.*']

Note: The Froala API offers additional options related to pasting content. These can impact how content is pasted from Word documents too. For instance, if you set the pastePlain API option to true, all pasted content is cleaned, regardless of the value of wordPasteKeepFormatting.

Let’s look at the other pasting options that affect pasting content whether it is from Word or other sources.

pastePlain

Indicates whether the rich text editor should strip formatting when pasting content or not. In both cases, the content structure is preserved. It is set to ‘false‘ by default. This keeps the text formatting.

new FroalaEditor('.selector', {

  pastePlain: true

});

Other options

The other options pasteDeniedTags, pasteDeniedAttrs, and pasteAllowedStyleProps are similar to wordDeniedTags, wordDeniedAttrs, and wordAllowedStyleProps respectively but they affect the content copied from any sources. 

 

Events

Events are callback functions that are triggered during the paste process. You can customize the editor’s behavior by handling these events in your application’s logic.  In this section, we will explore all the events related to pasting content as each one is critical for customizing the process.

paste.before

This event occurs before the paste action is performed. This lets you modify pasted content before it’s inserted into the editor or add custom logic.

 new FroalaEditor('.selector', {
   events: {

    'paste.before': function (original_event) {

      // Do something here.

      // this is the editor instance.

      console.log(this);

    }

  }

});

You will receive the jQuery event object for the paste event (original_event) as the first parameter. 

For example, if we paste this “Froala WYSIWYG editor is an easy yet powerful solution for reaching your goals.“ into the editor, the first argument will be 

{

paste: { target: p, clipboardData: DataTransfer }

bubbles: true

cancelBubble: false

cancelable: true

clipboardData: DataTransfer { dropEffect: "none", effectAllowed: "uninitialized", mozCursor: "auto", … }

composed: true

currentTarget: null

defaultPrevented: true

eventPhase: 0

explicitOriginalTarget: <div class="fr-element fr-view" dir="auto" aria-disabled="false" spellcheck="true" contenteditable="true">

isTrusted: true

originalTarget: <p>

returnValue: false

srcElement: <p>

target: <p>

timeStamp: 114314

type: "paste"

<get isTrusted()>: function isTrusted()

<prototype>: ClipboardEventPrototype { clipboardData: Getter, … }

}

paste.beforeCleanup (clipboard_html)

The event is triggered after the content has been pasted into the Froala Rich Text Editor but before any clean action is performed.

new FroalaEditor('.selector', {

  events: {

    'paste.beforeCleanup': function (clipboard_html) {

      // Do something here.

      // this is the editor instance.

      console.log(this);

    }

  }

});

In this event, you will receive the clipboard-pasted HTML (clipboard_html) string as the first parameter.

For example, if we paste this “Froala WYSIWYG editor is an easy yet powerful solution for reaching your goals.“ into the editor, the first argument will be:

  • In case you copied it from not Word document
<html><body>

<!--StartFragment-->Froala WYSIWYG editor is an easy yet powerful solution for reaching your goals.<!--EndFragment-->
</body>
</html>
  • In case you copy it from a Word document
<html xmlns:o="urn:schemas-microsoft-com:office:office"

xmlns:w="urn:schemas-microsoft-com:office:word"

xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"

xmlns="http://www.w3.org/TR/REC-html40">

<head>

<meta http-equiv=Content-Type content="text/html; charset=utf-8">

<meta name=ProgId content=Word.Document>

<meta name=Generator content="Microsoft Word 15">

<meta name=Originator content="Microsoft Word 15">

<link rel=File-List

href="file:///C:/Users/mostafa/AppData/Local/Temp/msohtmlclip1/01/clip_filelist.xml">

<!--[if gte mso 9]><xml>

 <o:OfficeDocumentSettings>

  <o:AllowPNG/>

 </o:OfficeDocumentSettings>

</xml><![endif]-->

<link rel=themeData

href="file:///C:/Users/mostafa/AppData/Local/Temp/msohtmlclip1/01/clip_themedata.thmx">

<link rel=colorSchemeMapping

href="file:///C:/Users/mostafa/AppData/Local/Temp/msohtmlclip1/01/clip_colorschememapping.xml">

<!--[if gte mso 9]><xml>

 <w:WordDocument>

  <w:View>Normal</w:View>

  <w:Zoom>0</w:Zoom>

  <w:TrackMoves/>

  <w:TrackForma…

Note: you can modify the pasted content by returning a new string.

paste.afterCleanup (clipboard_html)

The event is triggered after the content has been pasted into the Froala Rich Text Editor and cleaned up. The pasted content will be replaced with the returned string if one is returned. This allows users to manipulate the pasted content before it becomes a part of the editor’s content.

new FroalaEditor('.selector', {

  events: {

    'paste.afterCleanup': function (clipboard_html) {

      // Do something here.

      // this is the editor instance.

      console.log(this);

     // Return modified clipboard_html if needed.

      return clipboard_html;

    }

  }

});

You will receive the cleaned HTML as the first parameter.

For example, if we paste this “Froala WYSIWYG editor is an easy yet powerful solution for reaching your goals.“ into the editor, the first argument will be:

  • In case you choose to clean the content
<p>Froala WYSIWYG editor is an easy yet powerful solution for reaching your goals.</p>
  • In case you choose to not clean the content
<p style="margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:107%;font-size:15px;font-family:&quot;Calibri&quot;,sans-serif;">Froala WYSIWYG editor is an easy yet powerful solution for reaching your goals.</p>

paste.after

This event is triggered after the paste action has been processed and the content has been inserted into the editor. It allows you to perform additional actions once the paste is complete. It doesn’t have any parameters.

new FroalaEditor('.selector', {

  events: {

    'paste.after': function () {

      // Do something here.

      // this is the editor instance.

      console.log(this);

    }

  }

});

Paste Images from Word

Froala uploads images pasted from Word just like regular images. Since there are no specific API options or events for this, the pasting image process can be customized using general API options and events.

Image paste Options

pasteAllowLocalImages

Removes images that have a local path (file://) on paste. Enabling this option might result in having mixed content on HTTPS websites.

new FroalaEditor('.selector', {

  pasteAllowLocalImages: true

});

 imagePaste

Allows pasting images from clipboard.

new FroalaEditor('.selector', {

  imagePaste: false

});

imagePasteProcess

Use default image settings for pasted images.

new FroalaEditor('.selector', {

  imagePasteProcess: true

});

Image paste Events

image.beforePasteUpload (img)

Triggered before uploading a pasted image from clipboard to the server. The first parameter is the DOM element representing the image to be uploaded.

Note: Returning false in the handler assigned to the event will cancel the current action.

new FroalaEditor('.selector', {

  events: {

    'image.beforePasteUpload': function (img) {

      // Do something here.

      // this is the editor instance.

      console.log(this);

    }

  }

});

Demo

Take a look at the browser console to see the event results after pasting some content in the demo below

Conclusion

Implementing an online documents editor, such as Froala Editor is a powerful, time-saving solution. By properly configuring the editor, and adding the enhanced Microsoft Word and Excel Pasting Plugin, you can make it easier for users to compose and edit content in familiar formats, No more hassle of having to reformat text, lists, tables, and images copied from Word or Excel files. If you find anything that you believe should work differently, just reach our engineering team and we’ll get it solved.

Overall, Froala is an excellent solution for building online documents, creating messaging applications, or any form that requires rich text editing capabilities with a modern and intuitive user interface. Give the Froala Editor a try today and elevate your document editor game!

Creating a Page Builder Using the Froala WYSIWYG Editor

Creating An Amazing Page Builder Using The Froala WYSIWYG Editor

In today’s digital era, every business needs to have its own website, blog, etc. In fact, people may doubt your legitimacy as a business if you don’t have a website. However, getting a professionally designed website can be costly, due to which many businesses opt to build a website by themselves. You can use a WYSIWYG HTML editor to ease web content creation. A WYSIWYG editor essentially allows you to easily create and manage HTML content without writing any code. However, people usually use a rich text editor or WYSIWYG editor for composing documents or creating simple, one-block content. For more complex websites, most developers today use a web page builder. A website page builder allows you to create beautiful and well-formatted websites quickly without the need to write a single line of code.

In this article, we’ll show you how you can convert the Froala WYSIWYG editor into an easy-to-use, drag-and-drop page builder.

What Is A Web Page Builder?

 

A page builder built using the Froala WYSIWYG editor

If you don’t know how to code and want to create a website for your business, you want something that doesn’t involve learning and writing code. If you spend a lot of time learning programming languages to create websites, you wouldn’t be able to focus on growing your business and meeting customer demands. This is where you need a page builder or drag-and-drop website builder. A website page builder comes with built-in templates, layouts/themes, and other elements you need to create a professional web page. It is essentially a tool that even nontechnical people can use to create websites without writing any code and reduce development time.

Should You Use WYSIWYG HTML Editors Or Page Builders?

A WYSIWYG Editor shows you how your content would look on a web browser. It allows you to create and edit web content quickly without writing any code. For example, you can use WYSIWYG editors to format text, add links, create tables, insert images and videos, add links, and more. However, most users prefer a WYSIWYG HTML editor for creating simple web pages and composing documents.

For creating professional, complex layouts and websites, drag-and-drop website builders are mostly used. You can use a page builder in your content management system, email marketing software, or any other application. Because of their ease of use, drag-and-drop page builders have become so popular, especially among small businesses.

Why Should You Use Froala WYSIWYG Editor To Create A Page Builder?

 

An efficient page builder built using Froala WYSIWYG editor

Froala is considered one of the best WYSIWYG HTML editors that offers great features and a clean UI (user interface). You can even use plug-ins to add new features to the editor. However, you can also convert it into an easy-to-use, drag-and-drop page builder thanks to its initialization modes features. By using Froala editor to create a page builder, you can combine the benefits of creating a website page builder from scratch and using an existing page builder. For example, when you create a page builder from scratch, you can customize it as per your requirements. However, using an existing page builder eliminates the need to write lengthy code from scratch.

Here are some key reasons to use Froala editor to create your page builder:

  • Froala offers a simple API with detailed documentation and flexible features to develop an efficient page builder that meets your requirements. When you use Froala to create your page builder, you can save a lot of time and effort as you don’t have to build every single component of your page builder from scratch.
  • It generates high-quality HTML code to minimize the issues associated with existing page builders.
  • Froala pricing plans are very budget-friendly. Additionally, it offers discounts for startups, which makes it a perfect option for creating your page builder.
  • Froala is also a perfect choice for those who wish to have both a WYSIWYG editor and a drag-and-drop page builder. As a result, you can get both editors using the same code.

How To Build A Page Builder Using Froala WYSIWYG Editor?

When you’re building a page builder, you need to create two sections: a toolbar and an editing area. To create these sections, open your HTML file and add the following code:

<div class="row"> 
  <div class="col col-1"> 
 <!-- Toolbar contains different block-types will go here --> 
</div> <div class="col col-2"> <!-- Editing Area --> <div id=“editing-area"></div> </div> </div>

Creating The Toolbar

The toolbar of a page builder consists of several block types, such as:

  • Title Block
  • Text Block
  • Button
  • Image Block
  • Code Block
  • Link
  • CTA Block
  • Markdown Block

Using these blocks, you can quickly add a title, text, images, CTA, buttons (such as submit buttons), etc., to the editing area to create your website or web page.

Here is an example code for adding the title block to the toolbar of the page builder:

<li data-type="title" class="block-source float-left">
  <div class="text-center">
      <div>
          <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 122.88 120.26" style="enable-background:new 0 0 122.88 120.26" xml:space="preserve"><g><polygon points="0,14.54 0,0 49.81,0 49.81,14.54 36.93,17.03 36.93,51.7 85.98,51.7 85.98,17.03 73.1,14.54 73.1,0 85.98,0 110,0 122.88,0 122.88,14.54 110,17.03 110,103.31 122.88,105.79 122.88,120.26 73.1,120.26 73.1,105.79 85.98,103.31 85.98,70.3 36.93,70.3 36.93,103.31 49.81,105.79 49.81,120.26 0,120.26 0,105.79 12.8,103.31 12.8,17.03 0,14.54"/></g></svg>
       </div>
        <span class="text-center">Title</span>
   </div>
</li>

You can then use the following CSS code to modify the block style and format:

<style> 

html,body, .row{ 
  margin: 0; 
  padding: 0; 
  height: 100%; } 
.col{ float: left; 
}

.col-1{ 
  width: 22%; 
  height: 100%; 
  margin-right: 5%; 
  background-color: #eee; 
  border-right: 1px solid #c4c1c1; 
} 

.col-2{ width: 72%; 
  padding: 10px auto; 
} 

@media screen and (max-width: 676px) { 
  .col{ float: none 
  } 
  .col-1, .col-2{ 
    width: 100%; 
    height: auto; 
    border: none; 
    margin: 0; 
  } 
  .col-1{ 
    height:250px; 
  } 
} 

.text-center { 
  text-align:center 
} 

.block-source { 
  margin:0 0 18px 18px; 
  width:7rem; 
  height:7rem; 
  white-space:nowrap; 
  text-overflow:ellipsis; 
  background-color:#fff; 
  border:1px solid #bfc7d6; 
  -webkit-box-sizing:border-box; 
  box-sizing:border-box; 
  border-radius:6px; 
  display:-webkit-inline-box; 
  display:-ms-inline-flexbox; 
  display:inline-flex; 
  -webkit-box-pack:center; 
  -ms-flex-pack:center; 
  justify-content:center; 
  -webkit-box-align:center; 
  -ms-flex-align:center; 
  align-items:center; 
  color:#6c757d 
} 

.block-source:hover { 
  cursor:pointer; 
  border:1px solid #c6bbef; 
  -webkit-transform:translate(0); 
  transform:translate(0) 
} 

.block-source svg { 
  height:3.65rem; 
  width:3.65rem; 
  color:#bfc7d6; 
  fill:#bfc7d6 
} 

.block{ 
  margin: 20px 0; 
} 

</style>

When you add all the blocks and format them, your toolbar will look as follows:

 

Page builder UI

Adding Blocks To The Editing Area

The editing area will consist of all the blocks that the user chooses to add to the page. Hence, when a user clicks on a block in the toolbar, we need to:

  • Add an HTML element that corresponds to the selected block type in the editing area
  • Initialize the Froala editor on that element with the required options

To initialize the Froala editor, add the latest version of the Froala stylesheet inside the head:

 

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css">

Now, add the Froala latest version script before closing the body tag:

 
<script src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js" ></script>
 

Next, we have to add a click event listener to the Block Types. You can find the detailed tutorial on customizing each block type, adding the drag-and-drop editor functionality, and creating an amazing page builder with Froala here.

Do You Need To Test Your Web Page Builder?

Software testing

QA testing is an extremely important aspect of any software development project, including web apps and websites. With QA testing, we can ensure that we release high-quality software without any bugs or errors. In other words, software testing helps save time and costs and enhances the quality of software. For software testing, we need to write test cases related to functionality, performance, usability, and more. However, conducting and managing several different test cases manually can be time-consuming. As a result, most developers today use test management tools to organize, track, and manage test cases.

Which Is The Best Tool For Managing Test Cases For Your Page Builder?

 

TestRail Test Management Tool

If you’re looking for a robust test management tool, TestRail is the right option. TestRail is a powerful web-based test management tool that helps users to plan, organize, run, track, and manage test cases efficiently. TestRail also allows you to create agile test plans and streamline your testing processes to create high-quality software.

Here are the popular features of TestRail:

  • With TestRail, planning and running test cases is quick and easy. You can quickly start test runs and choose test cases based on powerful filters. Additionally, TestRail’s advanced interface makes it easy to execute your tests and record results. You can also group, filter, and organize your results efficiently.
  • With TestRail, you can even link tests to defects and requirements in GitLab, Atlassian Jira, GitHub Issues, and more.
  • TestRail provides a single collaborative platform to track and monitor all of your test activities and quality metrics. It allows you to track tests for browsers, mobile devices, and more.
  • TestRail enables users to quickly generate traceability reports. For example, you can generate detailed reports for projects, plans, milestones, and runs. You can also compare the results of different test runs and milestones.
  • With TestRail, you can track the status and progress of testing in real-time.
  • TestRail can easily be integrated with many project management tools and automation testing tools, such as JIRA, Jenkins, and Selenium.
  • TestRail enables developers to efficiently organize reusable test cases in folders.

Frequently Asked Questions (FAQs)

 

What is the best free WYSIWYG editor?

Froala is a leading WYSIWYG HTML editor that offers impressive rich text editing features. For example, you can format text, insert rich media, add custom themes, and much more using the Froala editor.

What are the key features of the best WYSIWYG editors?

A good WYSIWYG HTML editor like Froala has a modern design and offers a wide range of impressive features, such as text formatting, inserting rich media, media management, auto-formatting, etc. A powerful WYSIWYG editor also seamlessly integrates with CMS and other apps and offers live preview options.

Can you convert a WYSIWYG HTML editor into a page builder?

Not all WYSIWYG editors can be converted into a page builder. However, you can convert Froala editor into an impressive page builder, thanks to its initialization modes features.

Learn more about TestRail and its features here.

Building a solid drag-and-drop web page builder using Froala

Froala Page builder
A developer building an amazing page builder using Froala WYSIWYG Editor Modern page builders have revolutionized the way we develop website pages. They enable non-technical users to quickly and easily create complex website pages that are responsive and scalable. Clients love page builders because they can create stunning web pages without requiring expensive development resources and lengthy development cycles. They provide the ability to quickly design and maintain pages without needing extensive coding experience or deep technical knowledge. Page builders are used in content management systems (CMS) like WordPress, and it is one of the reasons that makes WordPress so popular. That’s because page builders make it easy for absolute beginners to build and maintain their website pages and blog posts. Page builders are also used on email management platforms like Mailchimp to enable users to easily create email templates without the need for HTML coding skills. Page builders are used in many cases under different names like “theme builders”, “template builders”, “website builders”, or “email builders”. If you are creating an application where users will need to write HTML code, then using a page builder will be the best solution. Page builders can help you retain your users while attracting new ones because of their top-notch user experience.

The difference between a classic editor (WYSIWYG editor) and a modern drag-and-drop editor

Usually, platforms implement two types of editors to eliminate the need for users to write any HTML or CSS code:
  1.  A classic editor or standard WYSIWYG editor
  2.  A drag-and-drop editor which divides the web page into rows, columns, and blocks, allowing users to easily create and maintain templates, edit each block’s content separately, and assemble template elements by dragging and dropping them into a new position.
Users tend to prefer classic editors for composing documents, messaging, or simple, one-block content; however, for constructing more complex, structured layouts like a web page, a drag-and-drop editor is typically used.

Should You Build a Custom Page Builder or Use an Existing One?

Before integrating a page builder into your product, it is important to consider whether you should create one from the ground up or utilize a readily available page builder. Doing thorough research into both options will help you make an informed decision. Utilizing an existing page builder is likely the best way to begin. There is no need to start from scratch when there are other tools available. However, it might be surprising to know that in some cases, creating a custom page builder is the right choice. While using an existing page builder eliminates the hassle and time associated with coding from scratch as the underlying code is already developed, creating a page builder from scratch can be beneficial in a number of ways. Firstly, it allows businesses to customize the page builder to exactly meet their requirements, which can be important in terms of making sure the page builder works with their existing website and other applications. Additionally, it provides businesses with full control over the design and functionality of their page builder, allowing them to tweak and adjust the interface and features as they see fit. It also avoids having to present users with an abundance of components and options that will not be used. Furthermore, creating a page builder from scratch can mitigate some of the issues associated with existing page builders. One of the most problematic issues is the creation of bloated HTML code that contains a large number of DOM nodes. This causes the issue of having an excessive DOM size that slows down your page performance. This issue can drive away website visitors. The generated HTML code could also be in a non-semantic format that can badly affect the SEO ranking of the page. In this article, we will demonstrate an intuitive solution to construct a page builder that combines the advantages of creating one from scratch and using an existing page builder while minimizing the drawbacks. A solution that uses Froala to build your page builder.  

Why should I use Froala to build a page builder?

By using Froala to create your page builder, you will be able to save a lot of time and effort that would otherwise be spent building every single component of your page builder from scratch. Additionally, Froala’s API offers powerful and flexible features that help develop a page builder that meets your exact specifications. Froala Editor also produces efficient and high-quality HTML code, allowing you to avoid the issues associated with existing page builders. Froala pricing plans are very cheap. Unlike other WYSIWYG editors, Froala doesn’t charge extra for premium features, number of users, or editor loads. Froala also offers discounts for startups. Moreover, Froala has a perpetual plan, allowing customers to purchase a release once and receive updates for one year after the purchase date. And they can use the last release they received forever. These reasons make Froala affordable despite its status as a premier and powerful editor, and this makes Froala a good starting point for building your page builder. Moreover, Froala is an ideal choice for those who want to have both a classic editor and a drag-and-drop page builder. With this solution, you can get the best of both editors using the same code, making your product codes more consistent and optimized. You may also be able to reduce the third-party libraries you are using, which in turn can result in your product running faster.

Can You Use a WYSIWYG Editor to Develop a Page Builder?

With the Froala WYSIWYG editor, you can develop a robust, fast, and elegant page builder that has various components. This is due to its unique initialization modes feature, which makes the editor behave differently depending on the element that it is initialized with.
Email created using Froala's page builder
A demonstration of using a custom page builder created using Froala editor for creating a professional email – no coding required!

How to build a page builder using Froala

We have a detailed guide that explains how to create a page builder using Froala. In that guide, you can see how easy it is to do so in a few steps. The guide will show you that you can build different types of blocks by simply changing the editor initialization options. In the guide, we explained how to create eight different blocks types using Froala: 1- Title Block 2- Text Block 3- Image Block 4- Button 5- Link 6- CTA Block 7- Code Block 8- Markdown Block You can look at Froala’s API options, methods, and events and start thinking about other blocks that Froala can create. Also, if you would like to add an option to one of the blocks, you can simply create a custom Froala button and assign the desired function to it. Furthermore, you can create a whole custom functionality by writing your own plugin to customize a block depending on your project details and requirements.

Conclusion

With its cost-effective, flexible, and customizable features, combined with its already existing powerful API, Froala provides a solution for developers looking to create a page builder from scratch with minimal effort. Froala is the only WYSIWYG editor that you can use to build both classic and modern page builders. Give it a try by starting your free trial today.
Let your community know if you enjoyed this post.

Integrating a WYSIWYG Editor with a Reliable and Lightning Fast File Uploading System

Integrating Froala WYSIWYG Editor with FIlestack

With more than a billion files uploaded to the web daily, it’s important to include a reliable, fast, secure, and intelligent file upload system in your application.

Imagine you are using a WYSIWYG editor to create a web page or an email, and you are about to finish what you are doing. You just need to upload one last image or attach an important file. You click on the insert file button, select your file, and click on the upload button. Suddenly, the uploading process is stopped, and the upload fails.  We have all gone through this several times, and we know just how annoying it is. Today, we will learn about the reliable Filestack file uploading service and how to integrate it with the Froala editor. This will not just add more reliability to your editor but also a complete and powerful upload service to your editor. It will led to a seamless uploading experience that your users will enjoy.

 

Why Filestack?

The default uploading system included in most WYSIWYG editors handles uploading files using basic methods to just display the file inside the editor. In this setup, it’s your task to handle saving the file onto your server. Most of these systems aren’t reliable enough to be used in poor network conditions or in bad quality of service conditions.

The top WYSIWYG editor on the G2 for more than two years, Froala WYSIWYG editor, has one of the best file managers and uploading features. Moreover, it comes with free SDK libraries that support many server-side languages. These SDKs help you handle saving and deleting files to and from your server quickly and easily. Nevertheless, by integrating Filestack with Froala, you will get an even more powerful file uploading service.

Filestack Intelligent Ingestion

Filestack introduces the Intelligent Ingestion (FII) feature. It intelligently detects network conditions, device type, and browser then makes automated decisions on how best to chunk a file to ensure it uploads successfully. Tests show that Filestack is more reliable than other uploading services like Google Drive, Plupload, and jQuery File Uploader.

Filestack Content Ingestion

Filestack guarantees up to 10x faster uploads. Unlike the other uploading services, Filestack’s Content Ingestion Network (CIN) uploads your file in two stages:

  1. The file is stored in the nearest Filestack Ingestion point-of-presence (POP), and a file URL (filelink) is generated almost immediately for your use.
  2. While you access the file, it is uploaded asynchronously to its final destination. A webhook is sent to you, notifying you that the file is stored properly, and your filelink automatically adjusts to point to the permanent cloud storage location.

This means that you do not have to wait until the file is stored in its final destination before using it in your application.

Filestack Integrated Storage Sources

It is worth mentioning that Filestack allows you to upload files from over 20 sources without any additional lines of code. When it comes to storing your files on the Filestack cloud storage service, all you need to do is set the storeTo parameter of the picker options.

//Code Example
const client = filestack.init(YOUR_API_KEY);

const options = {
   storeTo: {
     location: 'azure',
     path: '/site_uploads/'
   }
};

//Open file picker
client.picker(options).open();

Filestack Processing Engine

With the Filestack processing engine, you can transform various types of files, including images, documents, and videos. For instance, users will be able to apply filters, adjust image sizes, and perform many other image transformations. This will provide them with a rich in-app image editing experience.

Filestack Intelligence

And we can’t ignore the intelligence you will add to your application when you integrate it with Filestack. With features like:

  • Copyright Detection
  • Phishing Detection
  • Image Safe for Work Detection (SFW)
  • Video SFW
  • Virus Detection

You can detect any suspicious or illegal content and block it before it is stored on your server.

If your business requires adding tags to uploaded images or videos, integrating Filestack into your application is your best bet. The “Image Tagging” and “Video Tagging” Filestack features accurately detect related tags in your image or video. After detecting the tags, you can use them to automatically group and classify your files.

Filestack Workflows

With Filestack, you can set up your desired logic through a simple user interface and then apply it to the uploaded files by setting the workflow API option. You don’t need to be a programmer to use it.

const client = filestack.init(YOUR_API_KEY);

//set your workflow
const options = {
   workflows: [YOUR_WORKFLOW_ID]
};

//open the file picker
picker = client.picker(options).open();

And Much More..

Filestack has hundreds of features that you will definitely find useful in your application. We can’t cover all of them in a single blog post, so take some time to view all of Filestack’s features here.

 

Many of Filestack’s features are available for free. Take advantage of this right away.

How do I integrate Filestack with Froala?

The modular architecture of the Froala editor makes it easy to extend its functionality through plugins. Follow the steps below to create a custom plugin that uses Filestack’s file picker to insert images into the Froala WYSIWYG editor:

  • Use the custom plugin guide to create a new Froala plugin called “filestack”
  • Add plugin options to allow users to enter their Filestack API and their desired Filestack options.
// Add options for your plugin.
FroalaEditor.DEFAULTS = Object.assign(FroalaEditor.DEFAULTS, {

    //Allow users to set their Filestack options 
    filestackOptions: {

       displayMode: 'overlay',

       uploadInBackground: false,

       //accept images only since we are using Filestack for inserting images to the editor.
       accept: ["image/*"],
    },

    //Allow users to enter their Filestack API
    filestackAPI: '',
});
  • Inside the plugin initialization method, verify that the user entered the Filestack API correctly
//Verify that the user entered the Filestack API credentials
if(editor.opts.filestackAPI === 0){
  alert("The Filestack plugin is not active! You should set the filestackAPI option correctly.");
  return false;
}
  • We need to create a button that will open the Filestack file picker. Create a custom button following this guide.
/*First, create icon for the button. The icon will be the Filestack logo */
FroalaEditor.DefineIcon('filestackIcon', {SRC: 'https://i.ibb.co/YX5xjzw/Filestack-logo.png', ALT: 'Open Filestack file picker', template: 'image'});

/*Create a button with the name 'openFilePicker' */
FroalaEditor.RegisterCommand('openFilePicker', {

    type: 'button',
    icon: 'filestackIcon',
    title: 'Open Filestack File Picker',
        
    //Set a function to be called when the button clicked
    callback: function callback() {
    
    /* This button will be used to insert new images or to replace an existing image
    ** in case of doing a replace action, save the selected image so we can replace it later.
    */ 
    var selectedImage = this.image.get();

    //Init Filestack
    var client = filestack.init(this.opts.filestackAPI);

    /*
    ** Extend the filestack options to trigger the filestack plugin onUploadDone callback once the image is uploaded 
    ** We will define the onUploadDone method on the custom filestack plugin in the next step.
    */
    Object.assign(this.opts.filestackOptions, {
        //Set displayMode to 'overlay' to open the file picker with the minimum setup. Other modes require more steps to get the file picker visible when the openFilePicker button is clicked.
        displayMode: 'overlay',
        onUploadDone: (res) => {
          //Save the caret position, to be able to insert images in the caret position
          this.selection.save();
 
          //Trigger the filestack plugin onUploadDone function
          this.filestack.onUploadDone(res, selectedImage);
        },
    });

    // Open file picker
    client.picker(this.opts.filestackOptions).open();

   }

   plugin: 'filestack'
});
  • On the Filestack plugin, add the onUploadDone method to be executed when the image is uploaded successfully through Filestack
function onUploadDone(res, selectedImage){

    //If an image was selected beforehand, remove it first.
    if( typeof selectedImage !== "undefined" ){
        editor.image.remove(selectedImage);
    }

    //Insert the new images into the editor
    if( typeof res.filesUploaded !== "undefined" ){
      for (const file of res.filesUploaded) {
           //Restore the caret position
           editor.selection.restore();

           //Insert the uploaded image in the editor
           editor.image.insert(file.url, false);
       }
    }
}
  • Don’t forget to make the onUploadDone method publicly accessible
  return {
            _init: _init,
            onUploadDone: onUploadDone,
        }
  • In the HTML page:
    • Include Froala stylesheet and script
    • Include Filestack script
    • Include the new Froala filestack plugin script
<head>
    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Froala-Filestack integration demo</title>

    <!-- Froala Editor Stylesheet-->
    <link href='https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css' rel='stylesheet' type='text/css' />
</head>

<body>

    <!--Editor element-->
    <div id="editor"></div>

    <!-- Froala Editor JS-->
    <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js'></script>

    <!-- Filestack JS-->
    <script src="https://static.filestackapi.com/filestack-js/3.x.x/filestack.min.js" crossorigin="anonymous"></script>

    <!-- Froala filestack plugin JS-->
    <script type='text/javascript' src='froala-filestack-plugin.js'></script>

</body>
  • Finally, initialize Froala editor considering the following:
    • Include Froala’s Filestack plugin in the pluginsEnabled option
    • Include the new openFilePicker button in the toolbarButtons option and the imageEditButtons option
    • (optional) Set filestackOptions option based on your preferences
<script>

  // init Froala Editor
  new FroalaEditor('#editor',{

            //Add openfilepicker button to the edit image popup buttons
            imageEditButtons: ['openFilePicker', 'imageReplace', 'imageAlign', 'imageCaption', 'imageRemove', '|', 'imageLink', 'linkOpen', 'linkEdit', 'linkRemove', '-', 'imageDisplay', 'imageStyle', 'imageAlt', 'imageSize'],

            //Add openfilepicker button to the toolbar buttons
            toolbarButtons: {

               'moreText': {
                  'buttons': ['bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript', 'fontFamily', 'fontSize', 'textColor', 'backgroundColor', 'inlineClass', 'inlineStyle', 'clearFormatting']
                },
                'moreParagraph': {
                  'buttons': ['alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', 'formatOL', 'formatUL', 'paragraphFormat', 'paragraphStyle', 'lineHeight', 'outdent', 'indent', 'quote']
                },
                'moreRich': {
                   'buttons': ['openFilePicker', 'insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome', 'specialCharacters', 'embedly', 'insertFile', 'insertHR']
                },
                'moreMisc': {
                   'buttons': ['undo', 'redo', 'fullscreen', 'print', 'getPDF', 'spellChecker', 'selectAll', 'html', 'help'],
                   'align': 'right',
                   'buttonsVisible': 2
                }
            },

            //Add filestack plugins to the enabled plugins array
            pluginsEnabled: ['filestack', 'image', 'link'],

            /*
            ** To get your Filestack API, create a free Filestack account 
            ** https://dev.filestack.com/signup/free/
            */
            filestackAPI: "**************",
   });

</script>

Now, you will be able to upload images through Filestack and insert them in the Froala editor.

 

 
Automatically add captions to your images

You can use Filestacks’ artificial intelligence to automate many helpful tasks before inserting the images into the WYSIWYG editor. For example, in the following demo, we use Filestack to detect a related caption for the uploaded image and then insert the detected caption below the image automatically.

 

By Integrating Filestack with Froala, you will add a powerful uploading system to your WYSIWYG editor. It will make your editor even more robust with features ranging from advanced image processing to artificial intelligence-based processing. We assure you that with this integration, you can attend to every possible in-editor uploading need of your users. Besides, it’s free. So why not try it now?


Sign Up Filestack Free