#326: Design Pattern Deepdives: Tabs and InfoBox

Chris and Stephen pick out a couple of components from our design pattern library (which we talked about last here) and go into why they exist, what they do, what makes them complex, and the API choices. Relatively new to us is the idea of compound components which have, so far, been good to us as far as composing components in a way that makes them easier to use and more flexible.

Time Jumps

00:36 Using our pattern library

02:14 Tabs

10:22 Sponsor: Jetpack

12:21 What is our state?

15:01 It’s easy to implement tabs

22:05 Box component

Sponsor: Jetpack

We’re fans of Jetpack! You might recognize Instant Search right here in the CodePen docs. But we’re well aware that not everybody feels as strongly positively as we do. Last call here… have your say, tell us why you don’t use it if you don’t:

I have a one-question survey for anyone who is hesitant (or even has negative feelings) about Jetpack for WordPress sites. Trying to understand understand why by seeking exact reasons. https://t.co/euAEy0MXEK

— CSS-Tricks (@css) July 6, 2021

The post #326: Design Pattern Deepdives: Tabs and InfoBox appeared first on CodePen Blog.

Flatlogic Admin Templates banner

How to Use Material UI Icons In React

Introduction in Material UI Icons In React

Hello, Bonjour and Guten Tag to you.

We have said it many times before and we won’t get tired of repeating that there are no small things when developing a project. The reasoning behind this belief we have is that in the modern Digital Age you don’t just sell your product. You also sell experience, convenience and emotion, because modern times constitute the market’s oversaturation with possibilities for a potential customer. That’s why every little thing counts.

That being said, the focus of our today’s article – Material UI Icons, might very easily seem unimportant, but it is most definitely not. Material UI Icons, and particularly in connection to React, are there to help you perfect your project, whether it is a site, an app or anything else, and, thus, perfect your potential client experience, which can lead to the metaphorical scales of their choice weighing in your direction.

Don’t get us wrong, we don’t say that they alone can do it for you. We are talking about them as a part of a whole complex of small things. And we would surely talk about each and every one of them in their own time. But today we focus on React Material UI Icons and only on them in order to do them proper justice. That means looking at:

What they are;

How you can use them with React;

How to import a React Material-UI icon for your project.

 So, without further ado, let’s get to the first and the second points of the upper-mentioned list.

What Is Material UI Icons and How to Use Them

To put it bluntly, a Material UI Icons are a pack of ready-made icons that represents a command, file, device, or directory. They can also be used to represent frequent operations and savings, and are usually placed in application and/or toolbars. Such Icons are used with a purpose of creating an easy shortcut to any action on the site or in the app, as well as allowing to replace long word descriptions with an easily understandable icon for a user. Material UI Icons mainly consist of two components: SvgIcon and Icon.

When it comes to Material UI Icons, the SVG component serves as the SVG path child and converts it into a React component. This React component allows you to customize the icon’s style and the reaction it makes after a click. It should also be mentioned that the size of said Icon should be 24×24 pixels, but we are getting ahead of ourselves. The second component, which is the Icon component, is there to display an icon from any ligature-enabled icon font.

“What does it all have to do with React?” – you might ask. And the answer is quite simple: you can also use them when creating a project with React’s help, which is well and good, because it allows you to keep this task in your line of focus without a need to switch. And there are even no pitfalls, as the pack is ready-made and ready to use. Although, it should be said that Material UI Icons are not a be all and end all of UI Icons, as there are plenty of other packs on the market. So, why choose it? In our opinion, you should choose them, because they are slick, stylish, minimalistic, and are supported by all major platforms, as well as browsers. But the best part is that they were created by Google. And this mastodon of a corporation knows a thing or two about creating site components.

So, there you have it. Now, let’s take a closer look at the process of creating and using said icons in your project.

How to import a React Material UI icon for your project

So, let’s say you are creating a website for your awesome project and you want to make it more colorful, vibrant and, dare we say it, more internationally accessible. That’s where Material UI Icons can come to your rescue, as they tick all of the upper mentioned boxes. So, first of all, here’s a little guide to how you can add the ready-made Material UI Icons into your project.

Step 1. Installing Material UI framework. The first and foremost thing to do is to install Material UI framework in order to be able to work with all of its components. To do so, add one of the following command lines, depending on whether you do it with npm or yarn, into your project:

npm install @material-ui/core

yarn add @material-ui/core

Step 2. Installing Material UI Icons. The next step here would be to install the icons themselves into the project’s catalogue. Once again, there are two ways to do it: through yarn or through npm:

npm install @material-ui/icons

yarn add @material-ui/icons

These components use the Material UI SvgIcon component we have mentioned above to render SVG paths for each and every icon. This, in order, constitutes peer dependency on the next Material-UI release.

Step 3. Importing Material UI Icons. After the installation of the Material UI Icons into your project’s catalogue, your next step would be to import them by using one of the following two methods:

Method #1. This option would be safer than the second one, also it somewhat restricts the creative potential of the developer’s experience:

import AccessAlarmIcon from ‘@material-ui/icons/AccessAlarm’;

import ThreeDRotation from ‘@material-ui/icons/ThreeDRotation’;

Method #2. This option is less safe, but, on the other hand allows an experienced developer more creative freedom:

import { AccessAlarm, ThreeDRotation } from ‘@material-ui/icons’;

By using one of these methods, we’ve imported Access Alarm and 3D Rotation icons into our project and you would be able to see them next time you boot up your project in their default variation. But keep in mind, that all of the icons in Material UI framework have five different variations:

Filled variation (the default option);
Outlined variation;
Rounded variation;
Twotone variation;
And Sharp variation.

So, if you want to use any of these variations, you would need to append the theme name to the icon name. Also keep in mind that while Material Design icons use “snake_case” naming, @material-ui/icons use “PascalCase” for the naming.

Step 4. Adding CSS to Material UI Icons to change styles. Let’s assume that your project has its own YouTube channel and you would like to add the link to it to your site. Adding the full link would look rather unfitting on any site, so, using a Material UI icon of YouTube would be a fit here. And let’s also assume that for stylistic reasons you want it to be in red and white, just as the original logo. In that potential situation your next step would be to add CSS to your icon to make it appear the way you need. In that case your next move would be as follows:

import React, { Component } from ‘react’
import YouTubeIcon from ‘@material-ui/icons/YouTube’;
export class Maticon1 extends Component {
render() {
return (
<div>
<AppBar className=”mrg” position=”static”>
<Toolbar>
<div style={{ ‘paddingLeft’: “600px” }}>
Material UI Social media Icons</div>
</Toolbar>
</AppBar>
<YouTubeIcon style={{ ‘color’: “red” }}/><br></br>
</div>
)
}
}

export default Maticon1

In this example, Maticon1 is the component where we add social media icons. After that, don’t forget to add reference of this component in app.js file by doing the following:

import React from ‘react’;
import logo from ‘./logo.svg’;
import ‘./App.css’;
import Maticon1 from ‘./Maticon1’

function App() {
return (
<div className=”App”>
<Maticon1/>
</div>
);
}

export default App;

And, the next time you run your project you will see a beautiful small Material UI Icon of YouTube in red and white.

But what if you need an icon that is not in the default set of Material UI Icons? Well, in that case the SvgIcon wrapper we’ve already mentioned above would come to your rescue. It allows you to create custom SVG icons by extending the native <svg> element. Bear in mind that all the SVG elements should be scaled for a 24×24 pixels viewport. This way the resulting icon would be available to use as a child for other Material UI components that themselves use the icons, and would be available for customization with the viewBox attribute. You would also be free to apply any of the theme colors by using the color prop, as by default all the components inherit the current color. The code for customization would look the following way:

function HomeIcon(props) {
return (
<SvgIcon {…props}>
<path d=”M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z” />
</SvgIcon>
);
}

And the code for color setting would look the following way:
· <div className={classes.root}>
<HomeIcon />
<HomeIcon color=”primary” />
<HomeIcon color=”secondary” />
<HomeIcon color=”action” />
<HomeIcon color=”disabled” />
<HomeIcon style={{ color: green[500] }} />

And, after adding these lines, your icons would look the following way:

That is how you install and customize your Material UI Icons. Feel free to wield this power to decorate your project with all sorts of beautiful icons and somewhat secretly enrich your end-user’s experience with it.

Conclusions to Have

Coming to the end of this article, we are hoping that we’ve shown you that even the littlest of things are noteworthy in their own right on Material UI Icons example. But the best part about this whole ordeal is the fact that Material UI Icons are not even that small, as they help you project the idea of any of your project. Just like a mosaic that consists of lots and lots of small pieces that create a sight to see when working together.

It should also be mentioned once again that they are just exceptionally easy to integrate, customize and shape to your needs, making Material UI Icons a must-try and, eventually, a go-to for any project development.

And that is all for today. We wish you a very happy day, filled with small pleasant things to enjoy. And, as always, feel free to read up on any other of our articles.

See you in the next article.

You might also like these articles

Top 20 Best React Website Templates for React Developers [Free and Premium]

Best 10 IDEs for React.js for 2021

React vs. Vue: What Is Easier? What Is Trending? Detailed Guide With All +/- [2021]

The post How to Use Material UI Icons In React appeared first on Flatlogic Blog.

Flatlogic Admin Templates banner

#325: New Embed Modal

Chris and Stephen talk about the New Embed Modal. We got to re-architect the thing into our modern stack, using all our latest design patterns, and improve the UX of it quite a bit while we were at it. This is something like the 4th generation of that experience, and we’re already eyeing up future improvements. Such is the nature of software development.

Time Jumps

00:27 Embedding pens from CodePen is v important

01:43 Embed pen modal got a refresh

05:28 Working with our design system

08:34 Sponsor: Clubhouse

10:22 Should we save settings?

16:59 The ability to resize how tall embeds can be

19:56 Using our design pattern libraries

Sponsor: Clubhouse

Your project management tool should be a breeze to setup, at least mildly enjoyable to use, and help evolve your already existing development workflows so it’s easier to get things done. Does that describe your current tool? If it does, great! You can stop reading. If not, then Clubhouse could be the perfect fit. We’re project management built specifically for software teams and we’re fast, intuitive, flexible, powerful, and many other nice, positive adjectives. Delight the grumpiest scrum masters with Clubhouse.

The post #325: New Embed Modal appeared first on CodePen Blog.

Flatlogic Admin Templates banner

Top 20 Best React Website Templates for React Developers [Free and Premium]

React website templates. React Overview.
What can you build with the help of React templates? 
What is a good React web template? How to choose a website template to start building your project
The List of React website templates
The List of React admin dashboards
About Flatlogic

React website templates. React overview.

There are lots of templates on the web nowadays. And React website templates are among the most popular ones. Just imagine, React library has got 172k stars on GitHub and more than 10,636,147 weekly downloads on npm

Free React themes are extremely useful when it comes to web development in general, and specifically when building interactive user interfaces. React templates give you an opportunity to use dozens of components and widgets from scratch.

Check out React Bundle!

10 React templates for $299
1,000 unique components
More than 300 pages

We love React library and especially React templates for their flexibility and cross-platform ability, for their wide range of customizable and reusable components, such as headers, tabs, lists, grids, buttons, and many more. Frontend developers widely reuse and work with these components that speed up building their web projects.

What can you build with the help of React templates? 

With the help of free and premium ready Reactjs themes you can build various types of websites:

Landing pages
Portfolio websites
Ecommerce websites
News website
Social media websites
Video streaming pages
Blogs

Crowdfunding pages and many other projects.

How to Choose a Good React Website Template?

Choosing the right one website template may seem tricky enough, but it certainly depends on the type of website you need to create. We have picked up the top 10 basic principles for you to evaluate before choosing the best React website template:

Design quality
Code quality/code cleanliness
Documentation quality
Ease of installation
Update frequency
Variety of components
Maintenance and quality of support
Clients
Company experience
Price

We’ve selected the top 20 best react website templates, react js themes and admin dashboards in 2021, both free and premium for various needs. Choose your admin dashboard or website template consistently weighing all pros and cons.

Do you like this article? You can read also:

Top 20+ Bootstrap Dashboard Templates To Use Absolutely Free

The List of React Website Templates

1. eCommerce React Template

Image source: https://flatlogic.com/templates/ecommerce-react-template/

Ecommerce React Template is a newbie in the family of Flatlogic web themes, it was created by a talented React developer, Michael Daineka, and was finally launched in May, 2021. It is a fully working eCommerce store where we used Reactjs for the front-end, NodeJS for the back-end, PostgreSQL for storing the data, and Sequelize as ORM. The E-commerce React template is absolutely SEO-friendly thanks to server-side rendering by NextJS.

In the front-end part of our eCommerce template, you will find such features as the product descriptions page, landing page, categories pages, all support pages (contact, FAQ, about, etc.), and blog. The back-end part consists of CMS for blog, authentication, CMS for the store with an analytics dashboard, user management, and product management. We have also integrated Stripe payment systems in our eCommerce React template.

Demo
Price: $149

In Flatlogic we create web & mobile application templates built with React, Vue, Angular and React Native to help you develop web & mobile apps faster. Go and check out yourself!
See our themes!

2. Flone – Flone React template

Image source: https://live.hasthemes.com/html/3/flone-react-preview

Flone is a super neat, modern, and attractive Reactjs template with enhanced navigation for building eCommerce websites. The developers used Redux (v4.0.4) and React Hooks to create 25 home variations, 9 shop pages, 9 product details pages, and many more. It is an SEO-friendly template that is essential to your shop platform ranking.

Demo
Price: $24

3. Argon Design System

Image source: https://demos.creative-tim.com/argon-dashboard/

Argon Design system is not just a website template, but a complete design system with a rich UI package based on Bootstrap 4.

Argon design system template is a developer-friendly web solution made by creative Tim. This is a dashboard template called Argon Design System with more than 100 individuals ready to use components inside. The entire range of prebuilt components is really streamlined, vary in color, and are easy to use. The Argon design system template is fully open source.

Demo
GitHub

4. Zooki ReactJs Landing Page Template

Image source: http://zooki.react.themesbrand.com/

Zooki is a React page template built with Bootstrap 4.2.1, HTML5 & CSS3. It is mainly used for personal websites, applications, product showcases, and promo pages. There are lots of ready-made UI components for various needs and 8 types of home pages which you can check here. It is a responsive and well-documented website theme for creating professional landing pages really quickly.

GitHub
Demo
Price: $19

5. GoGo React/Redux Admin Template

Image source: https://gogo-react.coloredstrategies.com/app/dashboards/

Devil is in the detail, and that’s the best slogan that describes the GoGo React template which is made with the help of SASS, JS, HTML, CSS. GoGo has 10 color schemes, dozens of layouts and components. Try its right-click menu, video player, keyboard shortcuts, two panels menu, icons, keyboard shortcuts, video player and other important instruments for building any app faster.

Demo
Price: $24

6. Dorsin Landing Page

Image source: https://gogo-react.coloredstrategies.com/app

Dorsin React template is a template for building modern app landing, app template, app landing page, creative app landing page, app store, app website. The Dorsin template is based on React, Bootstrap 4.2.1, HTML5 and & CSS3. It has good code quality and highly customizable widgets and components. All the quintessential pages like Modern design pages, Login Page, Sign Up Page are included.

Demo
Price: $14

7. Exolot – React Multipurpose Landing Page Template

Image source: https://envytheme.com/tf-jsx-demo/exolot/home-one

Exolot React is a landing page template with perfect UI components and Retina-ready graphics. This React website business template looks stunningly on all types of screens and devices. It is a multipurpose template for building SaaS applications, software products, online bookstores, portfolios, and other frontend website designs. The list of main features is here:

– React 17+, Bootstrap 4.x & Sass
– HTML5 & CSS3
– Animate CSS
– AJAX contact form Submission
– AJAX subscriptions form Submission
– Mailchimp

Demo
Price: $17

8. Agency : Creative Business React Template

Image source: https://agency.dexignlab.com/react/demo/?storefront=envato-elements

Agency is an exhaustive ReactJs website template for building unique site designs. Agency has 7 types of homepage, blog, portfolio pages, Mailchimp, reCaptcha, React revolution slider,  online appointment form and dozens of other functionalities. This site template is perfect for building cooperative landing pages, consulting agencies and other commercial sites.

Demo
GitHub

9. Gatsby Simplefolio

Image source: https://gatsby-simplefolio.netlify.app/

This React website template was made by a frontend developer from Argentina, Jacobo Martínez. Gatsby Reactjs template was built mainly with JavaScript and SCSS. It’s an easily customizable template with configurable color schemes, fast image optimization and clean code.

Demo
GitHub

The List of React admin dashboards

10. React Material UI Admin Template Node.js

Image source: https://flatlogic.com/templates/react-material-ui-admin-node-js/demo

Thanks to Material UI, React material template has dozens of customizable components for building React apps faster. Material UI elements are highly responsive and are widely used in developing desktop and mobile apps. React Material UI components are well combined and modified. Each component of the web package template can be changed in color, hover, and style. Nodejs version of the template will ease the building of eCommerce stores.

Demo
GitHub
Price: $99

11. Sing App React

Page source: https://demo.flatlogic.com/sing-app-react/

Sing App React is a highly customizable dashboard perfect for accounting software, customer relationship management (CRM) system, email management, marketing automation, website analytics program, etc. Sing App template was made for lovers of UI aesthetics in icons, buttons, dashboard elements, and charts. With this dashboard, the owner of the website or platform can easily track orders and their success rate, as well as track social metrics such as the most popular referring social media sites and their corresponding URLs, monitor sales numbers and periods of growth, to better understand what makes users tick. Sing App React template has also a version with Java backend for the Java adherents.

Demo 
Price: $59

12. Jumbo

Image source: https://jumbo.g-axon.work/dashboard/crypto

Jumbo is a React Admin Template made with Material-UI design. Jumbo React template is cross-compatible with all modern browsers like  Chrome, Firefox, Safari, Opera, and Edge. It is an entirely free and responsive template made primarily with HTML files. Jumbo React template is one of the best admin dashboards for its price.

Demo
GitHub
Price: $24

13. Fuse React Admin Template

Image source: http://react-material.fusetheme.com/apps/dashboards/analytics

Fuse React Admin Template by withinpixels differs in components design, thanks to Google Material design. Redux Toolkit is used as a primary UI library. It has built-in authentication, 5 example apps, 20+ pages, lots of reusable React components and widgets, and more. Fuse Reactjs template will work not only as a template but as a valuable source to learn React functionality more.

Demo
Price: from $26

14. Sofia Free React template

https://flatlogic.com/templates/sofia-free-react-template

Sofia React template is a top-quality responsive React template made in May of 2021. It was built with Bootstrap 4.6, the latest version of React, React 17, and React Hooks, React Router v5 for routing, SASS for easily changing styles. It is a fairly clean website template with clear charts, different amazing layouts, lazy loading modules, etc. It’s a perfect template for building a healthcare website or web app. All these features of Sofia come absolutely free of charge.

Demo
GitHub

15. React Tabler

Image source: https://preview.tabler.io/

React Tabler is an open-source dashboard with a very consistent layout. React Tabler theme is full of essential components and widgets like interface, blog, gallery, pages and page errors, contact forms, card, blogs and more. React Tabler has in-depth documentation, dozens of UI elements, Flickr-like photo portfolio, error pages, login/register forms, and many more.

Demo
GitHub
Price: free

16. EasyDev

Image source: https://previews.aspirity.com/easydev/maps/map_with_request

EasyDev is a well-documented modern React dashboard template based on React Components and Bootstrap 4 Framework. You will enjoy different sales statistics widgets, audience by country, tons of other marketing analytics dashboards. Highly detailed documentation makes it one of the most convenient templates for developers. Use it for e-commerce, analytics platforms, sports, and other types of web or mobile applications.

Demo
Price: $28

17. Enlite Prime React Template

Image source: http://enlite.ux-maestro.com/app

Enlite prime is a full-stack ReactJS template with multi-language support (English, Deutsch, Arabic, Chinese, Bahasa Indonesia, Españo), and carefully crafted pages and reusable widgets. This recently updated dashboard was written in ES6, with the 12-Column grid. The website template is stuffed with more than 30 React components and beautifully designed widgets.

Demo
GitHub
Price: $18

18. User management React

Image source: https://flatlogic.com/templates/user-management-react

User Management React template is a simple and lightweight admin dashboard system for all the operations with users. Plus, this React template has social login and password recovery.  These templates make the entire user management process ingeniously simple and comfy.

Demo
Price: $99

19. Volt React Dashboard

Image source: https://demo.themesberg.com/volt-react-dashboard/

Volt React admin dashboard is designed by Themesberg in fresh blue colors. It has tons of 100 UI elements, made with React.js and Bootstrap 5, Sass preprocessing language. The documentation of this React template is more than top-notch. The dashboard has a free version, Volt React Dashboard, and an advanced version, Volt Pro React dash, that costs $89.

Github
Demo

20. Light Blue React Template

Light Blue React is an absolutely free open-source admin dashboard template built with React and Bootstrap 4. This React template is made in royal blue color and has been put together with the help of JavaScript and SCSS18.0%. Light Blue React is a perfect template with detailed documentation, clean code, and excellent support service. Inside you will get a dashboard sample with typography, tables, notifications, all the components like icons, charts and maps, chat, login, error page, and other quintessential UI elements.

The template has another enhanced version with Node.js, server-side rendering, and SEO optimization to even further speed up your development. Light Blue React admin template can be used to create analytics dashboards, E-Commerce apps, CRM, CMS, SASS web apps, and many other apps.

Demo
GitHub
Price: $59

About Flatlogic

At Flatlogic, we design solutions for businesses thanks to broad expertise in custom development. When our clients succeed, we succeed as well. We develop a keen understanding of our client’s business needs and provide the most functional website templates and admin dashboards with all the necessities inside. We are experts in web development and know a lot about admin themes, dashboard templates,  admin panel templates, free dashboard templates and themes, and other types of web solutions for developers.

Our mission is also in educating young professionals and giving them the right tools for building their web and mobile sites and applications. We share our knowledge in web development with love, wit, and empathy. We want to nudge you coding with a dedication to make this world a better place, more functional, and convenient in all senses.

Hop on over to the Flatlogic site, choose the dashboard template you need to start coding and create your site or app faster!

You might also like these articles

12+ React Boilerplates & Starter Kits For Developers In 2021
Best React Open Source Projects
React vs. Vue: What Is Easier? What Is Trending? Detailed Guide With All +/- [2021]

The post Top 20 Best React Website Templates for React Developers [Free and Premium] appeared first on Flatlogic Blog.

Flatlogic Admin Templates banner

jQuery vs JavaScript. Why we Removed jQuery from our Templates? [Updated 2021]

jQuery vs. JavaScript

JavaScript

What is JavaScript used for? JavaScript web development capabilities allow websites to perform actions such as refreshing specific parts of a page without reloading the entire website, displaying pop-up messages, or introducing animations into 2D or 3D graphics. Overall, the main impact is on client-side development, but JavaScript can now do server-side actions with Node.js. Node.js is a framework for running JavaScript code on the server.

Using jQuery saves JavaScript developers time because they don’t have to write code themselves. Plus, raw JavaScript is heavier than jQuery. Remember, the jQuery library only provides code for front-end development. If the site is complex, then jQuery will not be suitable for working on it in a large team, developing and maintaining it. For a landing page, only the stubborn will use pure js, and when working with a framework or in large projects, of course, jQuery will not work.
Large applications are sometimes written in jQuery, but they are difficult and expensive to maintain. You need to immerse yourself in the code and always be in the context of this library, otherwise after a month it will be difficult to understand what is written there.

In full-fledged frameworks (for example, Vue.js or Angular.js), the possibilities for normal operation are already out of the box. This is, first of all, a component-based approach to building interfaces and abstraction from the DOM. And anyone who comes to the team with knowledge of the framework will be able to understand the code – at least because there are generally accepted project structures, documentation, community and StackOverflow. Of course, jQuery also has a large community and also has documentation, but it seems to me that everyone there writes code for themselves. It is a question of choosing a convenient tool for a specific task. A simple page with a simple form can also be written in jQuery. But if all that you write is simple pages with forms, then this does not mean that you need to stop learning new things and get acquainted with modern frameworks. Most of the things jQuery has been useful for is already added to vanilla Javascript, and without any libraries.

jQuery

jQuery is one of the most well-known JavaScript libraries and one of the most highly criticized. Why that is? Well, the reason is that jQuery acquired enormous popularity and drew attention very quickly from its release date. And this glory was deserved. jQuery did AJAX, animation, and had great simplicity thanks to Sizzle selector engine. And the last, but not least – jQuery hid some incompatibilities between different browsers’ JavaScript implementations. But, if it is so amazing and useful, why we made this decision? 

Why?

Well, the time has changed since jQuery’s time of glory. jQuery allowed programmers didn’t go crazy during the browser wartime IE vs Netscape’s Navigator when browsers can’t agree on things and developers had to deal with specificities of them both. Today Google is full of articles like “you don’t need jQuery at all” – just try to google it. The most persistent readers might discover articles dating back to the 2015 year. They all are roughly the same and have identical reasons we fully agree with, so we are not going to waste time looking into all the details. We just highlighted the main reason for us to abandon this legendary library. And it is simple – all unique functionality that jQuery has been providing can be simply implemented with plain JavaScript. Here is the list of our key points:

Cross-browser compatibility is not a sore spot now

This issue is not a problem now since in 2019 browser support for JavaScript is more consistent than ever with new APIs. So what once was very complicated and painful is quite simple now without jQuery implementation. jQuery still stays a necessity when you deal with Internet Explorer 9 or earlier versions. The number of IE users is less than 10 percent of all Internet users. If we remember the Pareto principle where 80% of the effects come from 20% of the causes, the choice not to use a whole JS library just to get 10% of the effect seems very rational.

In Flatlogic we create web & mobile application templates built with React, Vue, Angular and React Native to help you develop web & mobile apps faster. Go and check out yourself!
See our themes!

Speed

jQuery provides useful functions to manipulate the DOM and the core of it is the selector engine called Sizzle, which contains 2000 + lines of code. So jQuery need to wrap up a bunch of operation to accomplish any manipulations with DOM, and if you know how to do that in plain JavaScript what is the point in adding extra steps? Furthermore, jQuery brings extra dependencies (which is extra for sure) in code, adds complexity and file size. Okay, you may say that it’s not that large: the default compressed build is about 73 KB, minified compressed is about 30, but it will make a difference for web app loading speed! 

Good code is easily manageable code 

That was the vital point why we decided to get rid of jQuery in our products. First of all, we make admin dashboard templates for you, we seek ways to improve the quality of our code to make it more friendly and easily understandable. We maintain up-to-date documentation, provide support and are looking at ways not only to make our products better, but also easier to use. So we need to build maintainable code, while with jQuery sometimes it’s less painful to rebuild code than change it. jQuery is not the best option to use if your code is supposed to be reused by others. 

And again… Why?

jQuery uses its way to avoid extending native objects. In the past extending native objects was considered a huge minus, and this has played a significant role in jQuery development. Calling $ (div) returns us not a link to a DOM element or the list of nodes, but some jQuery object. Nevertheless, jQuery can’t entirely avoid links to native DOM elements. You also often use libraries from different sources, some of them need jQuery, some not. This brings an unexpected consequence: we get a mix of native DOM elements, lists of nodes and jQuery objects at the end. 

And even if you stick to jQuery naming convention for jQuery objects (adding $ before a variable name) and simple variables that contain links to native elements, you face a bunch of mistakes when you forgot to use $() for non-jQuery objects. To avoid embarrassment it’s often ended with the use of $() for almost everything (just in case). And this “just in case” situation can be implemented several times for the same variable. Looks weird? But there was more. 

Even if you strictly abide by the variable naming convention, sometimes you need to call a native method for a DOM-element or run a function from code that is not dependent on jQuery, so your code gets a lot of transfers of objects from jQuery to native and vice versa. 

It leads us to the problem of complicated code refactoring to make it jQuery-free, adding new features and at least figure out what the hell is going on in the code that is written by another programmer. 

Check out Light Blue Vue!

Completely jQuery free Vue.js admin dashboard template!

Alternative libraries

We are sure that you might have heard about Angular, Vue and React. We touched them all in our products (Angular, Vue, React) and can say that we like them, especially one of them (don’t throw stones at us for bias, we were impartial judges and we ensure you that it was a fair competition). The number one is React for its ability to create a dynamic responsive and very friendly user interface. React JS library is very lightweight, fast, modern, and it brings us a very powerful platform for creating mobile apps – React Native. React brought in our world’s such apps like Facebook, Instagram, Netflix, Khan Academy and much more. We used React Native to develop an innovative product React Native Starter, an awesome mobile starter kit that allows you to make your mobile app for both iOS and Android at once, provides you with any UI components you possibly need, and saves up to 20 000$ in development. 

Check out Sing App Vue!

Completely jQuery free Vue.js admin dashboard template!

Does jQuery have the future?

Developers upgrade it constantly (the last update was on May 1st, 2019), its loved and respected library, and furthermore jQuery can offer you tons of plugins for all tasted and any needs. You look for a carousel? jQuery has a special plugin for you! ( You want responsive and draggable grid layouts? Get one! Your app needs photos recognition and face detector? No problems, jQuery can pick up a solution! For every your requirement jQuery presents a dozen of plugins to solve the problem. Almost every JS programmer made a jQuery plugin at least once in his life. And that is nice, but doesn’t solve the core issue: jQuery needs a rebuild. jQuery made a unique offer to programmers once and we were happy to accept it, but that time has passed and the web has changed, whereas jQuery has not. None update helps jQuery – it all the same will lose the younger, better-looking cousins (React, Vue, Angular) that have already got recognition and a significant portion of developers who call web community to abandon jQuery. And this trend is driving… 

We believe that jQuery needs to develop a new product, jQuery version new or jQuery – with all the respect from dev community to this library we sure everyone will give new jQuery a chance, but in the current version we don’t think that jQuery will survive. 

The last word from our team

Our conclusion is simple – we strive for the absence of redundant code and extra-dependencies. We don’t encourage you to get rid of jQuery in all your projects. jQuery is still updated, has a long history, a large number of adherents. Almost all 5+ years old web sites are based on this library. Also, there are a lot of useful plugins for any supposed function and a huge number of developers. So we don’t consider that jQuery is going to be forgotten coming years – it needs time. In the end, it took years of recoding for Github to transfer its platform to plain JavaScript.

You might also like these articles:

The post jQuery vs JavaScript. Why we Removed jQuery from our Templates? [Updated 2021] appeared first on Flatlogic Blog.

Flatlogic Admin Templates banner

Setting HTTP status code based on Exception in Slim 4

One thing that’s quite convenient is to be able to throw an exception with a valid HTTP code set and have that code sent to the client.

For example, you may have:

throw new RuntimeException(“Not Found”, 404);

With the standard Slim 4 error handler, this response is sent to the client:

$ curl -i -H “Accept:application/json” http://localhost:8888
HTTP/1.1 500 Internal Server Error
Host: localhost:8888
Content-type: application/json

{
“message”: “Slim Application Error”
}

Ideally we want the status code to be 404.

Option 1: Use an HttpException

The simplest solution is to use one of Slim’s HttpException classes:

use SlimExceptionHttpNotFoundException;

throw new HttpNotFoundException($request);

This is only useful in a Request Handler as you need a Request object, but the expected response is sent to the client:

$ curl -i -H “Accept:application/json” http://localhost:8888
HTTP/1.1 404 Not Found
Host: localhost:8888
Content-type: application/json

{
“message”: “404 Not Found”
}

Simple and easy!

Option 2: Override the ErrorMiddleware

There are situation when you can’t simply replace the exception thrown. For example, you’re updating an application from Slim 3 and you have hundreds of customised exceptions already throwing, or you throw from a class that doesn’t have a Request object instance available.

In these cases, the easiest solution is to extend the Slim ErrorMiddleware to wrap the exception in an

HttpException

and then the standard error handling and rendering will “just work”.

I’m feeling a little lazy, so let’s use an anonymous class to do replace the call to $app->addErrorMiddleware():

$container = $app->getContainer();
$logger = $container->has(LoggerInterface::class) ?$container->get(LoggerInterface::class) : null;

$errorMiddleware = new class (
callableResolver: $app->getCallableResolver(),
responseFactory: $app->getResponseFactory(),
displayErrorDetails: false,
logErrors: true,
logErrorDetails: true,
logger: $logger
) extends SlimMiddlewareErrorMiddleware {
public function handleException(
ServerRequestInterface $request,
Throwable $exception
): PsrHttpMessageResponseInterface
{
// determine that this exception should be wrapped. I’m checking for code between 400 & 599
if ($exception->getCode() >= 400 && $exception->getCode() < 600) {
// wrap the exception in an HttpException
$exception = new SlimExceptionHttpException(
$request,
$exception->getMessage(),
$exception->getCode(),
$exception
);
$exception->setTitle($exception->getMessage());
}
return parent::handleException($request, $exception);
}
};
$app->addMiddleware($errorMiddleware);

Behind the scenes of $app->addErrorMiddleware(), the SlimMiddlewareErrorMiddleware is constructed and then added to the middleware stack. We replicate that we an anonymous class that overrides handleException() to wrap the thrown exception if required.

Looking at the code in detail

There’s quite a lot going on here, so let’s break it down into parts.

$container = $app->getContainer();
$logger = $container->has(LoggerInterface::class) ?$container->get(LoggerInterface::class) : null;

$errorMiddleware = new class (
callableResolver: $app->getCallableResolver(),
responseFactory: $app->getResponseFactory(),
displayErrorDetails: false,
logErrors: true,
logErrorDetails: true,
logger: $logger
) extends SlimMiddlewareErrorMiddleware {

The constructor to SlimMiddlewareErrorMiddleware takes 6 parameters, so when we instantiate, we have to pass them all in though it’s not unusual for the $logger parameter to be left off in the call to $app->addErrorMiddleware(). The easiest way to get a logger instance if there is one, is to grab it from the container where it should be registered under the PsrLogLoggerInterface key which is imported into the file with a use statement.

I’ve used PHP 8’s named arguments as this constructor takes three booleans and it’s easier to remember what they do if they are labelled.

We then define the method for our class:

public function handleException(
ServerRequestInterface $request,
Throwable $exception
): PsrHttpMessageResponseInterface
{

Our anonymous class implements one method, handleException(), which extends the implementation in the parent. We then get to the meat of the method:

if ($exception->getCode() >= 400 && $exception->getCode() < 600) {
$exception = new SlimExceptionHttpException(
$request,
$exception->getMessage(),
$exception->getCode(),
$exception
);
$exception->setTitle($exception->getMessage());
}

The new work our implementation of handleException does is to wrap the thrown exception inside an HttpException. We only want to do this when the needed. One way to determine this is to check the error code; if the thrown exception has a code between 400 and 599, then it’s probably an HTTP error code. Of course this is not foolproof, so you may prefer to check that the class implements a particular interface.

To wrap, we instantiate a new HttpException, passing the thrown $exception as the last parameter, so that getPrevious() will find it. Then we set the message to display using setTitle() as that’s what’s used by the Slim error renderers.

Finally, we call through to our parent’s handleException() to do the work with our shiny new HttpException.

return parent::handleException($request, $exception);
}
};

We have defined and instantiated the class, so we add it to Slim’s middleware stack:

$app->addMiddleware($errorMiddleware);

and we’re done.

Checking that it works

Putting it all together, if we now throw an exception like this:

throw new RuntimeException(“Not Found”, 404);

then we get the expected HTTP response:

$ curl -i -H “Accept:application/json” http://localhost:8888
HTTP/1.1 404 Not Found
Host: localhost:8888
Content-type: application/json

{
“message”: “Not Found”
}

To sum up

The best way to get Slim’s error handling system to send the correct HTTP status code when throwing an exception is to thrown an exception that extends Slim’s HttpException. Otherwise, you can override Slim’s ErrorMiddleware to wrap your exception in an HttpException and you’re done.

Flatlogic Admin Templates banner

Create Liquid Swipe Effect In Your React Project With LiquidSwipe Component

Description:

Are you looking to create Swipe animation in your application? If yes then, you can use LiquidSwipe library to create liquid swipe effect in your React project. Lets see how.

How to use it?

1. Download the library using ‘Download’ button above and include in your component directory.

2. Then, import the component in your file. Like this.

import { LiquidSwipe } from ‘<relative-path-of-liquidswipe.js>’;

3. Here is the code that will create the liquid effect.

export const YourComponent = () => {
var componentsToRender = [] // Add components you want to render.
var backgroundColors = [] // Add background colors for each component.

return (

<LiquidSwipe
components={componentsToRender}
colors={backgroundColors}
/>

);
}

The post Create Liquid Swipe Effect In Your React Project With LiquidSwipe Component appeared first on Lipku.com.

Flatlogic Admin Templates banner

Python reverse NumPy array

In this Python tutorial, we will discuss Python reverse NumPy array with a few examples like below:

Python reverse array sort reverse
Python numpy inverse array
Python numpy invert array
Python numpy flip array

Python reverse numpy array

In this section, we will discuss Python reverse numpy array. We can easily use the list slicing() method to reverse an array in Python.
We actually create a new list in the reverse order as that of the original one.
Let’s take an example to check how to implement a reverse numpy array
Basically there are many ways to check reverse numpy array.
Using list slicing method
Using flip() function
Using reverse() function
Using flipud() method
Using fliplr() function
Using length() function

Using List slicing

In this method first, we will create a NumPy array and then use the slicing method.

Example:

import numpy as np

arr= np.array([1, 2, 3, 6, 4, 5])
result = arr[::-1]

print(“Reverse array”,(result))

Here is the Screenshot of the following given code

Python reverse numpy array

Using flip() function

In this method, we can easily use the Python function flip() to reverse an original array.
The flip() function is used to reverse the order of elements in an array along the given axis.
The flip() function is defined under numpy, which can be imported as import numpy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of numpy, which is a library in Python.
The shape of the array is preserved, but the elements are reordered.

Syntax:

Here is the Syntax of the flip() function

numpy.flip
(
arr,
axis=None
)

It consists of few parameters

arr: input array

axis: The default, axis=None, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis.

Example:

Let’s take an example to check how to implement a reverse NumPy array by using the flip() function.

import numpy as np

arr= np.array([9, 8, 3, 6, 2, 1])
result = np.flip(arr)

print(“Reverse array”,(result))

In the above example, we will first import a NumPy library and create a NumPy array using the function np. array. After that create a variable and assign the function np. fill in which passes an argument as an array and print the result. The output will display in the form of reverse order.

Here is the Screenshot of the following given code

Python reverse numpy array by the flip method

Using reverse() function

In this method, we can easily use the function reverse() to reverse an original array.
The reversed() function returns the reversed iterator of the given sequence.
It reverses an array at its original location, hence doesn’t require extra space for storing the results.
It is an inbuilt method in Python programming language that reverses objects of list in place.

Example:

Let’s take an example to check how to implement a reverse NumPy array by using the reverse() function.

import array

arr=array.array(‘i’,[4,5,9,1,9,3])
print(arr)

#reversing using reverse()
arr.reverse()
print(“Reversed Array:”,arr)

In the above example first, we will import an array library and then create an original array and pass string and array as an argument.

Here is the Screenshot of the following given code

Python reverse numpy array reverse method

Using flipud() method

In this method, we can easily use the flipud() method to reverse an original array.
The flipud() function is used to flip an given array in the up/down direction.
Flip the entries in each column in the up/down direction.
The flipud() function is used to shift the function from up to down.
The ud means Up / Down. The np.flipud() returns a view. Because a view shares memory with the original array, changing one value changes the other.

Syntax:

Here is the Syntax of flipud() method

numpy.flipud
(
array
)

It consists of few parameters

array: input array

Returns: Flipped array in up-down direction

Example:

Let’s take an example to check how to implement a reverse numpy array by using the flipud() method.

import numpy as np

arr= np.array([9, 8, 3, 6, 2, 1])
result = np.flipud(arr)

print(“Reverse array”,(result))

In the above example, we will first import a NumPy library and create a NumPy array using the function np. array. After that create a variable and assign the function np.flipud in which passes an argument as an array and prints the result. The output will display in the form of reverse order.

Here is the Screenshot of the following given code

Python reverse numpy array by flipud method

Using fliplr() function

In this method, we can easily use the fliplr() function to reverse an original array.
The np.fliplr() function flips the array(entries in each column) in left-right direction. The numpy flipr() function accepts an array as an argument and returns the array the same array as flipped in the left-right direction.
It reverse the order of elements along axis 1 (left/right).

Syntax:

Here is the Syntax of fliplr() function

numpy.fliplr
(
arr
)

It consists of few parameters

arr: input array

Returns: It returns an output array with the columns reversed. Since the operation is returned the operation

Example:

Let’s take an example to check how to implement a reverse NumPy array by using the fliplr() function.

import numpy as np

arr= np.array([[3, 5, 6, 7, 2, 1],
[2,5,6,7,8,9]])
result = np.fliplr(arr)

print(“Reverse array”,(result))

Here is the Screenshot of the following given code

Python reverse numpy array fliplr method

Using length() function

In this method, we can easily use the length() function.
We are going to begin by pointing to the first element within our given list. Take a start index variable which is equal to zero. After that we are going to the last element of our list which is end_index and that’s going to equal the length of our list.
So the length function itself is going to return as an integer value

Example:

Let’s take an example to check how to implement a reverse NumPy array by using the length() function.

def reverse(nums):

start_index = 0
end_index = len(nums)-1

while end_index > start_index:
nums[start_index],nums[end_index] = nums[end_index],nums[start_index]
start_index = start_index + 1
end_index = end_index -1

if __name__ == ‘__main__’:
n = [1,2,3,4,5]
reverse(n)
print(n)

Here is the Screenshot of the following given code

Python reverse numpy array using the length function

Python reverse array sort reverse

In this section, we will discuss Python reverse array sort reverse.
In Numpy, the sort() function does not allow us to sort an array in descending order. Instead, we can reverse an array utilizing list slicing in Python, after it has been sorted in ascending order.
The slice notation [::1] with default start and stop indices and negative step size -1 reverses a given list.
Use slicing notation s[start:stop:step] to access every step-th element starting from index start (included) and ending in index stop (excluded).

Example:

import numpy as np
arr = np.array([2, 5, 1, 6, 7, 2, 4])

sort_arr = np.sort(arr)
# Reverse the sorted array
reve_arr = sort_arr[::-1]
print(sort_arr)
print(reve_arr)

In the above example first we will import a numpy library and create an array using the np.array function. After that create a variable and arrange the elements using np.sort() function.
Reverse the sorted array using slicing method and print the result.

Here is the Screenshot of the following given code

Python reverse numpy array reverse method

Python numpy inverse array

In this section, we will discuss Python numpy inverse array.
For matrix inverse, we need to use numpy.linalg.inv() function.
This function will inverse the given matrix. The inverse of a matrix is such that if it is multiplied by the original matrix, it results in identity matrix.
It consists of one parameter that is A and A can be a matrix.
Python provides an easy method to calculate the inverse of the matrix. The function numpy.linalg.inv() is available in the Python numpy library.

Syntax:

numpy.linalg.inv(a)

Example:

Let’s take an example to check how to inverse an array in python

import numpy as np

a = np.array([[4,3],[2,7]])
inverse_matrix = (np.linalg.inv(a))
print(inverse_matrix)

In the above example first, we will import a numpy library and create an array using the np. array function. After that create a variable and assign the function np.linalg and display the result.

Here is the Screenshot of the following given code

Python numpy inverse array

Another method to check Python numpy inverse array

In this method, we can easily use the function np.matrix to inverse the elements of an array.
It Returns a matrix from an array-like object, or from a string of data.
A matrix is a specialized 2-D array that retains its 2-D nature through operations.
In this method we use the I attribute to inverse the elements of a given matrices.

Syntax:

Here is the Syntax of np.matrix()

numpy.matrix
(
data,
dtype=None,
copy=True
)

It consists of few parameters

data: it is interpreted as a matrix with commas or spaces separating columns, and semicolons separating rows.

dtype: Data type of the matrix

Example:

Let’s take an example to check how to inverse an array in python

import numpy as np

m = np.matrix([[4,6],[7,8]])
print (m.I)

Here is the Screenshot of the following given code

Python numpy inverse array matrix method

Python numpy invert array

In this section, we will discuss Python numpy invert array. Here we can easily use the function numpy.invert().
This function is used to compute the bit-wise inversion of an array element wise.
It Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays.

Syntax:

Here is the Syntax of numpy.invert()

numpy.invert
(
x,
out=None,
Where=True,
casting=’same_kind’,
order=’K’,
dtype=None
)

It consists of few parameters

X: input array (Only integer and boolean types are handled).

Out: Its an optional parameter. A location into which the result is stored. If provided, it must have a shape that the inputs broadcast.

Where: This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result.

Example:

Let’s take an example to check how to implement a numpy invert array

import numpy as np

arr= np.array([4, 5, 5, 6, 2, 1])
result = np.invert(arr)

print(“Invert array”,(result))

Here is the Screenshot of the following given code

Python numpy invert array

Python numpy flip array

In this section, we will discuss Python numpy flip array. For this we can easily use the function numpy.flip().
This function reverses the order of array elements along the specified axis, preserving the shape of the array.
The shape of the array is preserved, but the elements are reordered.

Syntax:

Here is the Syntax of the flip() function

numpy.flip
(
arr,
axis=None
)

Example:

Let’s take an example to check how to implement a reverse NumPy array by using the flip() function.

import numpy as np

arr2= np.array([4, 2, 3, 2, 1, 8])
res = np.flip(arr2)

print(res)

Python numpy flip array

You may like the following Python NumPy tutorials:

Python NumPy empty array with examples
Python NumPy nan
Valueerror: Setting an array element with a sequence
Python NumPy Average
Python NumPy absolute value with examples

In this Python tutorial, we will discuss Python reverse NumPy array with a few examples like below:

Python reverse array sort reverse
Python numpy inverse array
Python numpy invert array
Python numpy flip array

Flatlogic Admin Templates banner

Accessing PostgreSQL databases in Go

This post discusses some options for accessing PostgreSQL databases from Go.
I’ll only be covering low-level packages that provide access to the underlying
database; this post is not about ORMs, which were covered earlier in this blog. The full source
code accompanying this post is on GitHub.

We’re going to be using a simple data model that could serve as a basis for
an online course system (like Coursera):

There is a many-to-many relationship between courses and users (a user can take
any number of courses, and each course has multiple users signed up), and
a one-to-many relationship between courses and projects (a course has multiple
projects, but a project belongs to a single course).

The SQL to create these tables is:

create table if not exists courses (
id bigserial primary key,
created_at timestamp(0) with time zone not null default now(),
title text not null,
hashtags text[]
);

create table if not exists projects (
id bigserial primary key,
name text not null,
content text not null,
course_id bigint not null references courses (id) on delete cascade
);

create table if not exists users (
id bigserial primary key,
name text not null
);

create table if not exists course_user (
course_id bigint not null references courses (id) on delete cascade,
user_id bigint not null references users (id) on delete cascade,
constraint course_user_key primary key (course_id, user_id)
);

Note that the hashtags column is of the PostgreSQL array type: hashtags
text[]; this is on purpose, to demonstrate how custom PostgreSQL types are
modeled in the various Go approaches presented here.

database/sql with the pq driver

Probably the most common way to access PostgreSQL databases in Go is using the
standard library database/sql, along with pq
as the database driver. The full code for this approach, applied to our sample
database is available here;
I’ll present some relevant bits and pieces below:

import (
“database/sql”
“fmt”
“log”
“os”

_ “github.com/lib/pq”
)

// Check is a helper that terminates the program with err.Error() logged in
// case err is not nil.
func Check(err error) {
if err != nil {
log.Fatal(err)
}
}

func main() {
db, err := sql.Open(“postgres”, os.Getenv(“MOOCDSN”))
Check(err)
defer db.Close()

// … use db here
}

There’s the usual blank import of the driver package, which registers itself
with database/sql; thereafter, the “postgres” name can be used as a
driver name to pass to sql.Open. The path to the database is passed in an
env var; for example, it could be something like:

MOOCDSN=postgres://testuser:[email protected]/testmooc

If the database was created with the name testmooc, with the user
testuser having access to it.

Following this initialization, we can issue queries to the database via db.
Before we look at sample queries, here’s the data model translated to Go types:

type course struct {
Id int64
CreatedAt time.Time
Title string
Hashtags []string
}

type user struct {
Id int64
Name string
}

type project struct {
Id int64
Name string
Content string
}

Note that, unlike with ORMs, relationships between tables are not captured here.
A course does not have a collection of projects; this is something we
need to set up manually when querying the DB. Another thing to note is that
Hashtags has the type []string which will be mapped to PostgreSQL’s
text[].

Here’s a sample function wrapping an SQL query:

func dbAllCoursesForUser(db *sql.DB, userId int64) ([]course, error) {
rows, err := db.Query(`
select courses.id, courses.created_at, courses.title, courses.hashtags
from courses
inner join course_user on courses.id = course_user.course_id
where course_user.user_id = $1`, userId)
if err != nil {
return nil, err
}
var courses []course
for rows.Next() {
var c course
err = rows.Scan(&c.Id, &c.CreatedAt, &c.Title, pq.Array(&c.Hashtags))
if err != nil {
return nil, err
}
courses = append(courses, c)
}
return courses, nil
}

Given a user ID, this function obtains all the courses the user is signed up
for, by join-ing the courses table with the course_user linking table.
database/sql requires reading the result of the query in a scanning loop,
and manually placing the results into structs; it’s not aware of any mapping
between Go structs and SQL tables. PostgreSQL arrays are read by wrapping with a
pq.Array type.

Here’s a slightly more involved query, which joins three tables to
obtain all the projects the user has to finish (there could be multiple
projects per course, and a user could be signed up for multiple courses):

func dbAllProjectsForUser(db *sql.DB, userId int64) ([]project, error) {
rows, err := db.Query(`
select projects.id, projects.name, projects.content
from courses
inner join course_user on courses.id = course_user.course_id
inner join projects on courses.id = projects.course_id
where course_user.user_id = $1`, userId)
if err != nil {
return nil, err
}
var projects []project
for rows.Next() {
var p project
err = rows.Scan(&p.Id, &p.Name, &p.Content)
if err != nil {
return nil, err
}
projects = append(projects, p)
}
return projects, nil
}

While the SQL is more complicated, the rest of the code is almost identical to
the earlier function.

pgx

While pq has been around for a long time and has served the Go community
well, it hasn’t been very actively maintained recently. In fact, if you read
all the way to the end of its README, you’ll find this in the Status section:

This package is effectively in maintenance mode and is not actively
developed. Small patches and features are only rarely reviewed and merged.
We recommend using pgx which is actively maintained.

So what is pgx? It’s a driver and toolkit for PostgreSQL:

pgx aims to be low-level, fast, and performant, while also enabling
PostgreSQL-specific features that the standard database/sql package does
not allow for.

The driver component of pgx can be used alongside the standard
database/sql package.

The pgx package has two distinct modes of operation:

It can serve as a standard driver for database/sql.
It can serve as a direct interface to PostgreSQL, which isn’t beholden to
the standard API of database/sql, and thus can employ PostgreSQL-specific
features and code paths.

To use option (1), we can reuse 99% of the previous sample (the
database/sql interface is really very well standardized!). All we have to
do is replace the driver import with:

_ “github.com/jackc/pgx/v4/stdlib”

And then change the sql.Open call to invoke the pgx driver:

db, err := sql.Open(“postgres”, os.Getenv(“MOOCDSN”))

We don’t have to update the rest of the code [1].

What about the direct interface? For this, we’ll have to rejigger our code a
bit, since the types are slightly different. The full code for this is available
here;
here are the salient changes:

ctx := context.Background()
conn, err := pgx.Connect(ctx, os.Getenv(“MOOCDSN”))
Check(err)
defer conn.Close(ctx)

Instead of using sql.Open, we call pgx.Connect instead. When it’s
time to query the DB, our function for grabbing all the courses a user is signed
up for would be:

func dbAllCoursesForUser(ctx context.Context, conn *pgx.Conn, userId int64) ([]course, error) {
rows, err := conn.Query(ctx, `
select courses.id, courses.created_at, courses.title, courses.hashtags
from courses
inner join course_user on courses.id = course_user.course_id
where course_user.user_id = $1`, userId)
if err != nil {
return nil, err
}
var courses []course
for rows.Next() {
var c course
err = rows.Scan(&c.Id, &c.CreatedAt, &c.Title, &c.Hashtags)
if err != nil {
return nil, err
}
courses = append(courses, c)
}
return courses, nil
}

Note that the Go struct types representing table entries remain exactly the
same. Reading query results with pgx is very similar to database/sql,
but array types no longer need to be wrapped in pq.Array, since pgx
supports natively reading PostgreSQL arrays into Go slices.

So, what do we get by using pgx instead of database/sql? According to
the feature list on its README, quite
a lot, including native support for custom PostgreSQL types, JSON, an advanced
connection pool and a whole slew of performance-oriented features. Most notably,
pgx uses the PostgreSQL binary protocol directly for faster marshaling and
unmarshaling of types. According to pgx’s benchmarks, there are considerable performance
differences in some cases [2].

sqlx

We’ve seen a few examples of non-trivial SQL queries being scanned into Go
objects so far; all of them involve the same pattern:

The query is submitted
The result is iterated row by row
Each row gets manually unmarshaled into struct fields

One of the biggest complaints about database/sql in Go is the verbosity
of this process; particularly the second and third steps above. Why can’t we
just say:

var courses []course
db.FillInQueryResults(&courses, .)

After all, many packages in the Go standard library already work this way; for
example encoding/json, etc. The reason is the variety of types SQL supports.
While JSON has relatively few supported types, SQL has many; moreover, SQL types
differ by database. Therefore, it was fairly tricky for the Go project to offer
such advanced scanning capabilities in the standard library, and we have to rely
on third-party packages instead.

Luckily, an abundance of third-party packages exists just for this purpose.
One of the most prominent is sqlx. Let’s
revisit our sample database querying code, this time using sqlx. The full
code for this is available here.

The database setup code is very similar to the vanilla database/sql version:

import (
“fmt”
“log”
“os”

“github.com/jmoiron/sqlx”
_ “github.com/lib/pq”
)

func Check(err error) {
if err != nil {
log.Fatal(err)
}
}

func main() {
db, err := sqlx.Open(“postgres”, os.Getenv(“MOOCDSN”))
Check(err)
defer db.Close()

// … use db here
}

sqlx.Open wraps sql.Open and uses the same database driver registration
mechanism. The type it returns is sqlx.DB, which extends sql.DB with
some convenience methods. Here’s our function to query all courses a user is
signed up for, this time using sqlx:

func dbAllCoursesForUser(db *sqlx.DB, userId int64) ([]course, error) {
var courses []course
err := db.Select(&courses, `
select courses.id, courses.created_at, courses.title, courses.hashtags
from courses
inner join course_user on courses.id = course_user.course_id
where course_user.user_id = $1`, userId)
if err != nil {
return nil, err
}
return courses, nil
}

This is just what we wanted! The code scans the result into a slice of
course objects directly, without needing the row-by-row loop. sqlx
accomplishes this feat by using reflection – it examines the underlying type
of the struct in the slice and maps DB columns to struct fields automatically.
It sometimes needs help, though; for example, our course struct has to
be modified as follows:

type course struct {
Id int64
CreatedAt time.Time `db:”created_at”`
Title string
Hashtags pq.StringArray
}

Since sqlx won’t map the database created_at column to the CreatedAt
field automatically, we have to provide an instruction to do so explicitly in
a field tag.

sqlx requires an underlying database/sql driver for the
actual DB interactions. In the example above, we’ve been using pq, but
the stdlib driver of pgx can be used as well. Unfortunately, sqlx does
not support the native pgx driver
.
However, a different package called scany does support both the native and the
stdlib drivers of pgx. I wrote another version of this sample, using
scany; I won’t show this code here, since it’s very similar to the sqlx
example, but you can find it on GitHub.

Is sqlx worth it?

Looking at our dbAllCoursesForUser function, the version using sqlx
saves about 10 lines of code compared to the vanilla scan with database/sql.
I’m on record saying that ORMs are unlikely to be worthwhile in Go, but what about
sqlx? Is saving 10 LOC per DB query function worth the trouble of an
additional dependency, with its potential quirks, bugs and leaky abstractions?

This question is hard to answer globally, so I’ll just say “it depends”.

On one hand, 10 LOC per DB query is really not much. Say you have 50
possible SQL queries in your application, this saves 500 LOC of trivial and
repetitive code. Is that a lot? In most cases, almost certainly not. In the end,
it all boils down to the central thesis of the benefits of extra dependencies
as a function of effort
.

On the other hand, as opposed to ORMs, packages like sqlx and scany
provide a fairly focused utility with not very much magic involved. After all,
the standard library already has similar tools built in for unmarshaling JSON,
so this is a tried-and-true method that can work for data in relational
databases as well. Since the utility of these packages is focused, they are
not terribly hard to tear out of a codebase and replace, in case things don’t
go as expected, so they also present a considerably smaller risk than going
all-in on ORMs.

To conclude, packages like sqlx and scany provide a middle ground
between raw SQL access and full-blown ORMs; this means mid-of-the-way advantages
as well as disadvantages.

[1]
There’s a small nuance to be aware of if you’re following along with
the code samples, trying to run them. To be able to read PostgreSQL
arrays in Go using the database/sql driver component of pgx, we
still need to import pq in order to use its pq.Array type. This
type provides custom readers that are required to read custom DB types
via the standard interface. When using the pgx direct interface, this
is not necessary since pgx supports reading PostgreSQL arrays
directly into slices. See this pgx issue for additional information.

[2]
As usual with benchmarks, YMMV. Every case is different, and I
imagine that in many scenarios the network overhead of a PostgreSQL
connection will subsume any difference observable between different
drivers.

Flatlogic Admin Templates banner

A Simple Bootstrap Drop-down Menu For React

Description:

Create simple and beautiful Bootstrap drop-down menu for your React project. It will work just like a user setting drop-down menu on the top right. The drop-down menu will open on ‘Click’ event.

How to use it?

1. Install the component with npm.

npm install react-bootstrap-dropdown-menu –save

2. Include the Bootstrap library if not included in your project.

<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css” rel=”stylesheet” media=”all”>

3. Import the component.

import React from ‘react’;
import { DropdownMenu, MenuItem } from ‘react-bootstrap-dropdown-menu’;

4. Create the drop-down menu as following.

class SettingsMenu extends React.Component {
constructor() {
super();
this.deleteAccount = this.deleteAccount.bind(this);
this.logout = this.logout.bind(this);
}

deleteAccount(e) {
console.log(“Deleting Account”)
}

logout(e) {
console.log(“Logging out”)
}

render() {
return (
<DropdownMenu userName=”Chris Smith”>
<MenuItem text=”Home” location=”/home” />
<MenuItem text=”Edit Profile” location=”/profile” />
<MenuItem text=”Change Password” location=”/change-password” />
<MenuItem text=”Privacy Settings” location=”/privacy-settings” />
<MenuItem text=”Delete Account” onClick={this.deleteAccount} />
<MenuItem text=”Logout” onClick={this.logout} />
</DropdownMenu>
);
}
}

export default SettingsMenu;

The post A Simple Bootstrap Drop-down Menu For React appeared first on Lipku.com.

Flatlogic Admin Templates banner