Category: ReactJS

What’s new in liferay 7?

Liferay 7 was a major release that introduces several new features and improvements over previous versions of Liferay.

Here are some of the notable new features in Liferay 7:
  1. Modular architecture: It will allows developers to build and deploy individual components as separate modules with modular architecture. This makes it easier to develop, test, and deploy Liferay components.
  2. React-based UI: Liferay 7 introduces a new UI framework built with React, a popular JavaScript library for building user interfaces. The new UI framework provides a modern, responsive, and intuitive user experience.
  3. Content Management System (CMS): Liferay 7 includes a new CMS that provides an intuitive and easy-to-use interface for managing content, pages, and sites. The CMS allows users to create and manage content without the need for technical skills.
  4. Personalized experiences: Liferay 7 introduces features for creating personalized experiences for users based on their preferences, behaviors, and interests. This includes features for segmenting and targeting audiences, and for personalizing the content and layout of pages.
  5. Improved performance: Liferay 7 includes faster page loading times, improved scalability, and reduced resource utilization.
  6. Improved security: Liferay 7 includes several security improvements, including support for OAuth2 and OpenID Connect, improved password policies, and enhanced access control.
  7. Microservices support: Liferay 7 includes support for building and deploying microservices, which are small, independent, and modular components that can be deployed and managed separately. This allows developers to build and deploy Liferay components as microservices, making it easier to manage and scale their applications.

These are just some of the new features and improvements in Liferay 7. If you are considering upgrading to Liferay 7, it is important to carefully evaluate your specific needs and requirements, and to consult with an expert in Liferay development.

Understanding React Pure Components

Many people are confused by the difference between a Functional Component and a Pure Component. Most of them think that they are the same, but this is not true. When you use a React Pure Component, We need to import PureComponent from React:

If your React component’s render method is “pure” (that means it renders the same result, given the same props and state), you can use this function to improve the performance of your application. A Pure Component performs a shallow comparison for the props and nextProps objects as well as the state and nextState objects. Pure components do not include the¬†shouldComponentUpdate(nextProps, nextState)¬†method, and if you try to add it, you‚Äôll get a warning from React.

In this article, you’ll learn to create a basic example to understand how Pure Components works. To begin, you need to install the Chrome extension React Developer Tools to do a simple debug in your application. Download React Developer Tools from https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi.

Building your React application

First, create your React application using create-react-app. Once that is done, you can proceed to create your first React component.

Before you install create-react-app, remember that you need to download and install Node from www.nodejs.org. You can install it for Mac, Linux, and Windows.

Install create-react-app globally by typing this command in your Terminal:

Alternatively, you can use a shortcut:

Now build your first React application by following these steps:

  1. Create your React application with the following command:

  1. Go to the new application with cd my-first-react-appand start it with npm start.
  2. The application should now be running at http://localhost:3000.
  3. Create a new file called js inside your src folder:

File: src/Home.js

  1. You may have noticed that you are exporting your class component at the end of the file, but it’s fine to export it directly on the class declaration, like this:

File: src/Home.js

  1. Now that you have created the first component, you need to render it. So, open the jsfile, import the Home component, and add it to the render method of the App component. If you are opening this file for the first time, you’ll probably see a code like this:

To get started, edit src/App.js               and save to reload.

File: src/App.js

  1. Now change this code a bit. You need to import your Home component and then add it to the JSX. You also need to replace the <p> element with your component, like this:   

File: src/components/App.js

  1. Now, create the Numbers component:

File: src/components/Numbers/Numbers.js

  1. Then, create the Result component (as a Class Component):

File: src/components/Numbers/Result.js

  1. Finally, create the styles:

File: src/components/Numbers/Numbers.css

How React Pure Component works…

If you run the application, you will see this:

  1. You have used an input with the number type, which means you’ll only accept numbers if you start writing numbers (1, then 2, then 3, and such). You will see the results of the sum on each row (0 + 1 = 1, 1 + 2 = 3, 3 + 3 = 6):

Now, inspect the application using React Developer Tools. You need to enable the Highlight Updates option:

After this, start writing multiple numbers in the input (quickly), and you will see all the renders that React is performing:

As you can see, React is¬†doing¬†a lot of renderings. When the highlights are red, it means the performance of that component is not good. Here’s when React Pure Components will help you. Migrate your Result component to be a Pure Component:

File: src/components/Numbers/Result.js

Now if you try to do the same with the numbers, see the difference:

With the Pure Component React, you do less renders in comparison to a Class Component. Probably, you may now think that if you use a Stateless component instead of a Pure Component, the result will be the same. Unfortunately, this won’t happen. If you want to verify this, change the Result component again and convert it into a Functional Component.:

File: src/components/Numbers/Result.js

See what happens with the renders:

As you can see, the result is the same as the Class Component. This means that using a Stateless Component will not help you improve the performance of your application all the time. If you have components that you consider are pure, consider converting them into Pure components.

If you found this article interesting, you can explore Carlos Santana Roldan’s React Cookbook to be on the road to becoming a React expert. React Cookbook has over 66 hands-on recipes that cover UI development, animations, component architecture, routing, databases, testing, and debugging with React.

How to Work with the Latest JS features in React

Working with the latest javascript features in React

React is mainly written with modern JavaScript (ES6, ES7, and ES8). If you want to take advantage of React, there are some modern JS features that you should master to get the best results for your React applications.

In this article, you’ll learn the essential JS features so that you are ready to start working on your first React application.

How to do it

In this section, you’ll see how to use the most important JS features in React:

  • let and¬†const: The new way to declare variables in JavaScript is using¬†let¬†or¬†const. You can use¬†let¬†to declare variables that can change their value but in a block scope. The difference between¬†let¬†and¬†var is that¬†let¬†is a block scoped variable that cannot be global, and with¬†var, you can declare a global variable, for example:

  • The best way to understand block scope is by declaring a¬†forloop¬†with¬†var¬†and¬†let. First, use¬†var¬†and see its behavior:

  • If you write the same code with¬†let, this will be the result:

  • With¬†const, you can declare constants, which means that the value can’t be changed (except for arrays and objects):

  • If you declare an array with¬†const, you can manipulate the array elements (add, remove, or modify elements):

  • Also, using objects, you can add, remove, or modify the nodes:

  • Spread operator:The spread operator (…) splits an iterable object into individual¬†values. In React, it can be used to push values into another array, for example when you want to add a new item to a to-do list utilizing¬†setState:

  • Also, the Spread operator can be used in React to spread attributes (props) in JSX:

  • Rest parameter:The¬†rest¬†parameter is also represented by¬†…. The last parameter in¬†a function prefixed with¬†…¬†is called the rest parameter. The¬†rest¬†parameter is an array that will contain the rest of the parameters of a function when the number of arguments exceeds the number of named parameters:

  • Destructuring:¬†The destructuring assignment javascript feature is the most used feature in React. It is an expression that allows you to assign the values or properties of an iterable object to variables. Generally, with this, you can convert your component props into variables (or constants):¬† ¬†

  • Arrow functions: In Javascript ES6 provides a new way to create functions using the¬†=> These functions are called arrow functions. This new¬†method¬†has a shorter syntax, and the arrow functions are anonymous functions. In React, arrow functions are used as a way to bind the¬†this object in your methods instead of binding it in the constructor:

  • Template literals:¬†The template literal is a new way to create a string using backticks ( ) instead of single quotes (‘ ‘)¬† ¬†or double quotes (” “). React uses template literals to concatenate class names or render a string using a ternary operator:
  • Map: The¬†map()method returns a new array with the results¬†of calling a provided function on each element in the calling array. Map use is widespread in React and mainly used to render multiple elements inside a React component.For example, it can be used to render a list of tasks:

  • assign(): The¬†Object.assign()method is used to copy the values of all¬†enumerable own properties from one or more source objects to a target object. It will return the target object. This method is used mainly with Redux to create immutable objects and return a new state to the reducers:

  • Classes: JavaScript classes, introduced in ES6, are mainly a new syntax for the¬†existing¬†prototype-based inheritance. Classes are functions and are not hoisted. React uses classes to create class¬†Components:

  • Static methods: Static methods are not called on instances of the class. Instead, they’re called on the class itself. These are often utility functions, such as functions to create or clone objects. In React, they can be used to define the¬†PropTypes in a component:

  • Promises:The¬†Promise¬†object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Use promises in React to handle requests using axios or fetch; also, you can use Promises to implement server-side rendering.
  • async/await:¬†The async function declaration defines an asynchronous function, which returns an¬†AsyncFunction This can also be used to perform a server request, for example, using axios:

If you found this article interesting, you can explore React Cookbook, which covers UI development, animations, component architecture, routing, databases, testing, and debugging with React. React Cookbook will save you from a lot of trial and error and developmental headaches, and you’ll be on the road to becoming a React expert.

Customizing a Simple Social Media Application Using MERN

Learn how to use the MERN stack to build simple social media application features in this tutorial by Shama Hoque.

MERN Social

MERN Social is a sample social media application, used for the purpose of this article, with rudimentary features inspired by existing social media platforms such as Facebook and Twitter. In this article, you‚Äôll learn how to update a user profile in MERN Social that can display a user uploaded profile photo and an about description.

The main purpose of this application is to demonstrate how to use the MERN stack technologies to implement features that allow users to connect and interact over content. You can extend these implementations further, as desired, for more complex features.

The code for the complete MERN Social application is available on GitHub in the repository at github.com/shamahoque/mern-social. You can clone this code and run the application as you go through the code explanations. Note that you will need to create a MERN skeleton application by adding a working React frontend, including frontend routing and basic server-side rendering of the React views for following these steps.

The views needed for the MERN Social application can be developed by extending and modifying the existing React components in the MERN skeleton application. The following component tree shows all the custom React components that make up the MERN Social frontend and also exposes the composition structure that you can use to build out extended views:

Updating the user profile

The skeleton application only has support for a user’s name, email, and password. However, in MERN Social, you can allow users to add their description and also upload a profile photo while editing the profile after signing up:

Adding an about description

In order to store the description entered in the about field by a user, you need to add an about field to the user model in server/models/user.model.js:

Then, to get the description as input from the user, you can add a multiline TextField to the EditProfile form in mern-social/client/user/EditProfile.js:

Finally, to show the description text added to the about field on the user profile page, you can add it to the existing profile view in mern-social/client/user/Profile.js:

With this modification to the user feature in the MERN skeleton code, users can now add and update a description about them to be displayed on their profiles.

Uploading a profile photo

Allowing a user to upload a profile photo will require that you store the uploaded image file and retrieve it on request to load in the view. For MERN Social, you need to assume that the photo files uploaded by the user will be of small sizes and demonstrate how to store these files in MongoDB for the profile photo upload feature.

There are multiple ways of implementing this upload feature considering the different file storage options:

  • Server filesystem: Upload and save files to a server filesystem and store the URL to MongoDB
  • External file storage: Save files to an external storage such as Amazon S3 and store the URL in MongoDB
  • Store as data in MongoDB: Save files of a small size (less than 16 MB) to MongoDB as data of type Buffer

Updating the user model to store a photo in MongoDB

In order to store the uploaded profile photo directly in the database, you can update the user model to add a photo field that stores the file as data of type Buffer, along with its contentType in mern-social/server/models/user.model.js:

Uploading a photo from the edit form

Users should be able to upload an image file from their local files when editing the profile. You can update the EditProfile component in client/user/EditProfile.js with an upload photo option and then attach the user selected file in the form data submitted to the server.

File input with Material-UI

You can use the HTML5 file input type to let the user select an image from their local files. The file input will return the filename in the change event when the user selects a file in mern-social/client/user/EditProfile.js:

To integrate this file input with Material-UI components, you can apply display:none to hide the input element from view, then add a Material-UI button inside the label for this file input. This way, the view displays the Material-UI button instead of the HTML5 file input element in mern-social/client/user/EditProfile.js:

With the Button‘s component prop set to span, the Button component renders as a span element inside the label element. A click on the Upload span or label is registered by the file input with the same ID as the label, and as a result, the file select dialog is opened. Once the user selects a file, you can set it to state in the call to handleChange(…) and display the name in the view in mern-social/client/user/EditProfile.js:

Form submission with the file attached

Uploading files to the server with a form requires a multipart form submission. You can modify the EditProfile component to use the FormData API to store the form data in the format needed for encoding type multipart/form-data.

First, you need to initialize FormData in componentDidMount() in mern-social/client/user/EditProfile.js:

Next, you need to update the input handleChange function to store input values for both the text fields and the file input in FormData in mern-social/client/user/EditProfile.js:

Then, on clicking submit, this.userData is sent with the fetch API call to update the user. As the content type of the data sent to the server is no longer ‘application/json’, you‚Äôll also need to modify the update fetch method in api-user.js to remove Content-Type from the headers in the fetch call in mern-social/client/user/api-user.js:

Now if the user chooses to upload a profile photo when editing profile, the server will receive a request with the file attached along with the other field values.

Processing a request containing a file upload

On the server, to process the request to the update API that may now contain a file, you need to use the formidable npm module:

Formidable will allow you to read the multipart form data, giving access to the fields and the file, if any. If there is a file, formidable will store it temporarily in the filesystem. You need to read it from the filesystem, using the fs module to retrieve the file type and data and store it in the photo field in the user model. The formidable code will go in the update controller in mern-social/server/controllers/user.controller.js as follows:

This will store the uploaded file as data in the database. Next, you‚Äôll need to set up file retrieval to be able to access and display the photo uploaded by the user in the frontend views.

Retrieving a profile photo

The simplest option to retrieve the file stored in the database and show it in a view is to set up a route that will fetch the data and return it as an image file to the requesting client.

Profile photo URL

You need to set up a route to the photo stored in the database for each user and also add another route that will fetch a default photo if the given user has not uploaded a profile photo in mern-social/server/routes/user.routes.js:

You need to look for the photo in the photo controller method and if found, send it in the response to the request at the photo route; otherwise, you‚Äôll need to call next() to return the default photo in mern-social/server/controllers/user.controller.js:

The default photo is retrieved and sent from the server’s file system in mern-social/server/controllers/user.controller.js:

Showing a photo in a view

With the photo URL routes set up to retrieve the photo, you can simply use these in the img element’s src attribute to load the photo in the view in mern-social/client/user/Profile.js. For example, in the Profile component, you‚Äôll get the user ID from state and use it to construct the photo URL.

To ensure that the img element reloads in the Profile view after the photo is updated in the edit, you need to also add a time value to the photo URL to bypass the browser’s default image caching behavior.

Then, you can set the photoUrl to the Material-UI Avatar component, which renders the linked image in the view:

The updated user profile in MERN Social can now display a user uploaded profile photo and an about description:

If you found this article helpful, you can explore Shama Hoque’s Full-Stack React Projects to unleash the power of MERN stack. This book guides you through MERN stack-based web development, for creating a basic skeleton application and extending it to build four different web applications.

 

Most popular JavaScript frameworks in 2016

In this modern web JavaScript is the most popular language in the web to building the web application. There are many different ways to build modern web application with JavaScript, including a lot of different tool choices, and a lot of new theory to learn.Using the JavaScript we can easily extend the functionalities and logical executions of the component.

Most of the developer are used JQuery along with JavaScript to extend the features of HTML component,but when we talk about the large application it requires more effort and complex in code to develop and the maintain a large application. JavaScript Frameworks help to build fast,interactive and scalable web applications (which includes both single page and multiple page applications).

But, unfortunately! Most programmers find it hard to decide which framework¬†they use¬†and learn. Thus, in this article, I am going to highlight the 7¬†most popular¬†JavaScript Frameworks in 2016. Let’s get started!

2016-most-popular-framework

7 most popular JavaScript Frameworks in 2016

1. AngularJS

When we talked about javascript frameworks the first word comes in our mind is that AngularJS. AngularJS, as this is the most commonly used JavaScript Framework by javascript developers. It released in 2009, javaScript based open-source front-end framework to create web application or SPA (Single page application) mainly maintained by Google.

It supports the¬†MVC (Model‚Äďview‚Äďcontroller),MVVM (Modal-view-ViewModal) and MVW¬†(Modal-View-Whatever) design paradigm which supports standard two-way data binding. In MVW, whatever stands for ‚Äúwhatever works for you‚ÄĚ. Angular gives you the lot of flexibility to separate presentation logic from business logic and presentation state. In MVC, your data is updated on both the UI (presentation state)¬†and back-end (coding or server side) whenever it detects some changes in the engine.

As the UI components (View) are separated from the Model components, you can easily build reusable components for amazing and user-interfaces!

Recently Angular 2.0 has been released in OCT 2016, which claims to improve the speed & performance of mobile and desktop and take it further via web workers and server-side rendering. Meet huge data requirements by building data models on RxJS, Immutable.js or another push-model. Angular Loved by Millions of developers across the globe and it’s highly recommended for anyone who wants a powerful MVC framework with a strong and modern infrastructure that takes care of everything for you to build single page applications.

Angular is also planning to release Angular 4.0 then it called ‚ÄėAngular‚Äô

Video: See the announcement yourself

(Note: This is my personal favorite JavaScript Framework till date)

2. React

React (sometimes styled React.js or ReactJS) is an open-source JavaScript library which provides a view for data rendered as HTML. Components have been used typically to render React views which contain additional components specified as custom HTML tags. React gives you a trivial virtual DOM, powerful views without templates, unidirectional data flow and explicit mutation. It is very methodical in updating the HTML document when data changes; and a clean separation between components on a modern single-page application. React also support sever-side rendering with with nodejs

As your app comes into existence and develops, it’s advantageous to ensure that your components are used in right manner and React app consists of Reusable components, which makes code reuse, testing, and separation of concerns easy.

ReactJS is not only ‚ÄúV‚ÄĚ in MVC, it has stateful components, it handles mapping from input to state changes, and it renders components. I would highly recommend this Framework if you just need a front-end development Framework to build an incredibly complex and awesome UI through the power View Layers. In this sense, it does everything that an MVC does.

Apart from Facebook and Instagram, there are several companies that use React, including Whatsapp, BBC, PayPal, Netflix, Dropbox, etc.

3. Ember

Ember.js is open-source javascript frameworks like angular and react. Initially it released in 2011, 5 year ago. It has a huge active community online, so whenever  you face any problem, you can ask them.

Ember.js is based on¬†Model‚Äďview‚Äďviewmodel (MVVM)¬†design pattern, which is slightly different than MVC, In the sense that the view model is more than view and handles most if not all of the view‚Äôs display logic

For the fast server-side rendering with nodejs and adding  the animation in UI. we need to use Ember CLI addon Fastboot.js and liquid-fire.js, so the applications have extremely enhanced performance of complex UI with animation.

Ember supports Handlebars integrated templates that update the data changes automatically. It also provides routes, dependency injection, declarative two-way data binding and Custom components.

In 2015, Ember was best JavaScript Framework, competing against AngularJS and React, which should be enough to convince you about its usability and desirability in the JavaScript framework,there are several big companies who’s using ember.js Yahoo!, Zendesk, GROUPON, Yapp, MHElabs, TILDE.

I have not worked much in ember.js but as per my knowledge i¬†would highly recommended this JavaScript Framework to those who don’t necessarily need great flexibility or a large infrastructure, and just prefer to get things done for coping with deadlines.

4. Knockout.js

This JavaScript framework was initially released by Steve Sanderson in 2010 as open source under MIT license. Knockout works under the MVVM design paradigm and that makes it a little different from Ember and Angular.

Knockout has no dependencies on any other libraries and it supports all mainstream browsers like IE 6+, Firefox 3.5+, Chrome, Opera, Safari (desktop/mobile) it’s not popular as much competitors like Angular, Ember or Backbone. The slow growth is simply because of improvements and adding more features in framework.

Developer community is slowly moving to frameworks like React and Angular. Knockout has a great capability and can definitely make a come back but only if someone else adopts it and starts improvement it with the latest web JavaScript technologies.

You can read more about Knockout at knockoutjs.com.

5. Meteor.js

If you LOVE developing the website in pure javascript then MeteorJS is for you. It’s the full stack platform for building modern end to end mobile and web applications completely in JavaScript, for all environments: Application server, Web browser, and Mobile device.

Meteor is the child of Meteor Development Group, it was first released in 2012 as an open source JavaScript framework under MIT license.

Ever since its release, the MeteorJS community too is vibrant and helpful. You would find tons of resources, tutorials and custom packages that give super powers to solve your development errors and develop your app in MeteorJS.

The best thing about MeteorJS is that you use only JavaScript for front-end and backend application development, no need to invest time learning anything else.

The server side packages run in the node.js and you do not need do anything else but MeteorJS packages to access the database, all in JavaScript, this makes developer life easy for building real time web applications.

From Performance perspective, any changes in the database are reflected back on the UI in the real time and vice versa without the handshake between different languages with minimal development efforts.

You can read more about Meteor at –¬†meteor.com.

6. Vue.js

Vue.js is another¬†open-source JavaScript framework was released in 2014.¬†It supports¬†extremely simple API for developing the¬†Reactive¬†components for Modern Web Interfaces¬†Like Ember, it also uses the¬†Model‚Äďview‚Äďviewmodel (MVVM)¬†design paradigm which helpes in the simplification of the design.

The most important feature in this framework is that you can use selective modules with it for your specific needs. For example, you need to write HTML code, fetch the JSON and create a Vue instance to create the small effects that can reused!

Similar like others JavaScript Frameworks, it also uses two-way data binding to update the model and view, plus it also uses binder for communication between the view and data binder. If you thinking that is full-fledged framework to focus on it then I must say it’s not like what you thinking because it’s focuses entirely on the View Layer, so you would need to take care of other components on your own or you can use any other framework with them.

If you are familiar with AngularJS, then you will feel comfortable with this too, as it heavily incorporates the architecture of AngularJS, so many projects can be easily transferred to this Framework if you know the basics of JavaScript.

As I didn’t get chance to work with that but if you just want to get things done or gain JavaScript programming experience, or if you need to learn the nature of different JavaScript Frameworks you should try this.

7. Backbone.js

This framework¬†can be easily integrated to any third-party template engine, however, by default it has dependancy on Underscore¬†templates¬†along with¬†JQuery,¬†It has the¬†RESTful JSON¬†interface with the support of¬†MVC (Model‚Äďview‚Äďcontroller)¬†design pattern.

If you ever heard or used the famous social news networking service reddit, then you will be interested to hear that it uses the Backbone.js for several of its single-page applications. Jeremy Ashkenas who developed the Backbone.js, it has also created the Underscore templates as well as CoffeScript, so you are assured that the developer knows his stuff.

This framework provides models with key-value, views and several modules within a single bundle, so you don’t need to download the other external packages, saving you time. The source-code is available on Github, which means you can further modify it for your needs.¬†There are several big companies who‚Äôs using backbone.js 500px Web, Airbnb, Pinterest, Reddit, WordPress.com, USA Today.com,LinkedIn Mobile.

Conclusion

So, I have just highlighted the 7 most popular JavaScript Frameworks in this article in the hopes that it will help you choose the best JavaScript Framework for your tasks.

If you‚Äôre still having trouble to choose¬†the best JavaScript Framework for your learning or build web application for your project, then please understand the project requirement and client expectations; and if it doesn’t then just try the next one. Rest assured though that any Framework from the list will be good enough.

The best way to learn code is to write code!!!