blog

Remote React App Developer- Best And Most Underrated Pattern Design

<Modal showCloseButton&gt;
	<title&gt;Modal title</title&gt;
	<contents&gt;Modal body text goes here.</contents&gt;
	<dismissButton onClick={close}&gt;Close</dismissButton&gt;
	<actionButton&gt; onClick={save}&gt;Save</actionButton&gt;
</Modal&gt; 

The times are near when we would like to pass props and would want to control the behavior of child elements. For example, in the picture given below, you can see there are different elements:

  • A title section that is written at the top.
  • A cross button to close the action present at the top right corner.
  • A content area where you can write some text.
  • A button to save the changes, “Save changes”.
  • A dismiss button to close it, “Close”.

Now, if we want to reuse the Modal properly, we must modify the modal and its elements. This means that users will get control over things such as the content which is displayed, the dispatched events, the style of the content, and all other elements of the Modal that will be under the control of the user. Users can select a naïve solution for the acceptance of proposed for each element like they are:

<Modal
  showCloseButton
  showDismissButton
  showActionButton
  title="Modal title"
  contents="Modal body text goes here."
  dismissButtonText="Close"
  actionButtonText="Save changes"
  handleDismiss={close}
  handleAction={save}
/&gt;

The problem with this kind of approach is that it spams the mechanism of propos, and this makes the whole component look less readable and more inflated. While on the one hand, it is less attractive, at the other end, it limits the amount of propos that users can pass to child elements. This method also prevents users from having complete control over the elements. However, you can solve this problem through another way by providing generic props objects where every prop object is representing a different element:

<Modal
  showCloseButton
  title="Modal title"
  contents="Modal body text goes here."
  dismissButtonProps={{
    text: 'Close',
    handler: close,
  }}
  actionButtonProps={{
    text: 'Save changes',
    handler: save,
  }}
/&gt;

However, this solution works fine, but it does not solve the issue of spam, and you are completely abusing the syntactic sugar that JSX provides you in this way. You are obligated to use JSONs style attributes instead of using the HTML style attribute assignments (attr= “value”).

Using Bootstrap for the rescue

They take a very shrewd approach in Bootstrap, and that is instead of defining props all over the places, they gave us the capability to manipulate the Modal’s children directly. Now, we can achieve this intended functionality by using the dedicated components that Bootstrap was aiming for:

<Modal.Dialog&gt;
  <Modal. Header closeButton&gt;
    <Modal.Title&gt;Modal title</Modal.Title&gt;
  </Modal.Header&gt;

  <Modal.Body&gt;
    <p&gt;Modal body text goes here.</p&gt;
  </Modal.Body&gt;

  <Modal.Footer&gt;
    <Button variant="secondary" onClick={close}&gt;
      Close
    </Button&gt;
    <Button variant="primary" onClick={save}&gt;
      Save changes
    </Button&gt;
  </Modal.Footer&gt;
</Modal.Dialog&gt;

As you can see, the progress is there, and things are getting better, but we can take it to the next level. 

Although things are very declarative and clear and we can stay here, but we are still obligated to compose an entire modal to the next level. But this would mean that we would not be able to use the Modal’s children to cover up the missing pieces, as we implemented the part of the logic before. Normally, it is not like that we have to write the Modal’s content from scratch.

Moreover, you can use it as a template for your use in future cases. However, there is no filter or restriction on the children’s input, and you can use it the way you want. But normally, we would like it if the user uses only a few limited elements so that he does not mess up the things, and if that is the case, we must see what could be the right approach to follow it.

Introducing the design pattern that contains everything

Now, if we see our last progress and calculate what we gathered so far, the new pattern should have the following attributes:

  • Has complete control over child elements using props.children.
  • Has a template already in place for the user.
  • No spamming of the mechanism of props.
  • Has restrictions on the input.

Well, this sounds good and promising so let’s take a look at an example and we will be using the Bootstrap Modal component it as an anchor:

const ModalFromTheFuture = ({ showCloseButton, children }) =&gt; {
  const childProps = useChildProps(props.children, [
    'title',
    'contents'
    'dismissButton',
    'actionButton',
  ]);

  return (
    <Modal.Dialog&gt;
      <Modal.Header closeButton={showCloseButton}&gt;
        {childProps.title &amp;&amp; <Modal.Title {...childProps.title} /&gt;}
      </Modal.Header&gt;

      <Modal.Body&gt;
        {childProps.contents &amp;&amp; <p {...childProps.contents} /&gt;}
      </Modal.Body&gt;

      <Modal.Footer&gt;
        {childProps.actionButton &amp;&amp; <Button {...childProps.actionButton} variant="secondary" /&gt;}
        {childProps.dismissButton &amp;&amp; <Button {...childProps.dismissButton} variant="primary" /&gt;}
      </Modal.Footer&gt;
    </Modal.Dialog&gt;
  );
};

Now you can clearly view that the new modal component uses a hook known as “useChildProps(). Moreover, this hook will basically flatten nested propos by going through the ‘props.children’.  Furthermore, when it will come to make sure that right names are addressed, this method will validate them against a provided white list.

const useChildProps = (children, whitelist) =&gt; {
  return useMemo(() =&gt;
    [].concat(children).reduce(
      (childProps, child) =&gt; {
        if (whitelist &amp;&amp; !whitelist.includes(child.type)) {
          throw Error(`element <${child.type}&gt; is not supported`);
        }

        childProps[child.type] = child.props;

        return childProps;
      },
      [children]
    )
  );
};
<ModalFromTheFuture showCloseButton&gt;
  <title&gt;Modal title</title&gt;
  <contents&gt;Modal body text goes here.</contents&gt;
  <dismissButton onClick={close}&gt;Close</dismissButton&gt;
  <actionButton onClick={save}&gt;Save changes</actionButton&gt;
</ModalFromTheFuture&gt;

However, we know it will cause confusion with native HTML tag names, but this can be said about any other React component being used by other users or us. But if you see the changing trends, such as the introduction of component-based user-interface, for example, Angular, Vue, React, or other web components, so new tag names are not rare now. Therefore, you should go for the new design and must not stay afraid of getting hands on it.

If you need to hire Remote React App Developer then you can contact me.

How TYPESCRIPT can be used with NODE and EXPRESS?

In the start of my career , i was a web developer and i noticed that strong typed languages were dominant in market. I was impressed with new upcoming features in java script and python language. The idea of not declaring the variables made me more productive and i used to like my work. the first time i heard about Typescript the idea seemed like taking steps back to old days.

Full Stack Sofware Developer.,Full Stack Aws Serverless Application Developer., Full-Stack Developer.,Javascript Developer.,typescript with node and express

what changed my mind?

I had a strategy that, for individual projects I used simpler languages like java script but while working in a team or working on large scale I preferred using typescript. in this article i will try to explain the reason.

Full Stack Sofware Developer.,Full Stack Aws Serverless Application Developer., Full-Stack Developer.,Javascript Developer.,typescript with node and express

TYPESCRIPT

If you don’t have any know how of typescript i recommend to read the following overview:

https://www.tutorialspoint.com/typescript/typescript_overview.htm

and view the following: https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html

Comparison of Productivity and Maintenance

Typescript is an object oriented language used for app development. This means that the setup of project is remunerated with the maintenance of large scale projects. Lets see why it is so:

type safe= less errors

When we define the type in our code we allow the IDE to find out the errors and bugs while using the functions and classes that would be viewed by us at runtime.

Example:

function add (a: number , b: number):
number { return a+b;}
let mySum: number;
mySum=add(1,"two");
let myText: String;
myText=add(1,2);

I have used visual studio code and there is an error i.e “Two”

on line 4: error as string parameter is passed to a function that can only accept number

on line 6: error as assign to a string , the output gives a number .

these two errors would have gone unnoticed without typescript, showing bugs at runtime.

Project Modules exposed by IDE

There are hundreds of classes which are scattered across different files. When we declare types the IDE finds the origin files and relate the objects with them.

Full Stack Sofware Developer.,Full Stack Aws Serverless Application Developer., Full-Stack Developer.,Javascript Developer.,typescript with node and express
Full Stack Sofware Developer.,Full Stack Aws Serverless Application Developer., Full-Stack Developer.,Javascript Developer.,typescript with node and express

Programmers face difficulty in maintaining this language that is why they avoid transferring from java and C# to js but typescript helps in overcoming this obstacle.

Setting up express project with Typescript

lets see the steps taken to set up project in Express.js project :

npm init

install typescript package

npm install typescript -s

Typescript node package

Typescript cant be run in node.js engine rather it only runs java script. The node typescript package is used as transpiler for .ts files to .js scripts. Babel is used as typescript for trans-piling. however the market standard is to use Microsoft package for this purpose.

the script tsc is put inside the package.json :

“scripts”: {
“tsc”: “tsc”
},

This can be used to call typescript functions by using command line. below command is used:

npm run tsc — –init

this help in initializing the typescript by creating the file tsconfig.json . In this file we will remove comment i.e  outDiroption and choose transpile location to deliever .js files :

Full Stack Sofware Developer.,Full Stack Aws Serverless Application Developer., Full-Stack Developer.,Javascript Developer.,typescript with node and express

Express.js installation

npm install express -s

As typescript dont know express class type so express and typescript are independent. A special npm package can be used to recognize express class:

npm install @types/express -s

HELLO WORLD

Below is an example:

https://expressjs.com/pt-br/starter/hello-world.html

var express=require( 'express' ) ; 
 var app = express(); 
app.get( '/'function (req,res){
res . send( 'Hello World! ' ) ;
});
 app.1isten(3000, function ( )
 { 
console. log( ' Example app listening on port 3000! ')
});

now create folder app and inside it create file app.ts using following code:

// lib/app.ts
import express = require('express');

// Create a new express application instance
const app: express.Application = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

COMPILATION OF FIRST APPLICATION

npm run tsc

this command creates a build folder and .js file:

Full Stack Sofware Developer.,Full Stack Aws Serverless Application Developer., Full-Stack Developer.,Javascript Developer.,typescript with node and express

Running EXPRESS

node build/app.js

on port 3000 we can see our output:

Full Stack Sofware Developer.,Full Stack Aws Serverless Application Developer., Full-Stack Developer.,Javascript Developer.,typescript with node and express

Transcript running by not using transpiling

Typescript can be run directly on the node by using the package of ts-node . it is used for development purpose . For final deployment or embedding use java script code. version .The ts-node is included as dependent component on another package, tts-node-dev. After the installation of ,ts-node-dev we should run commands to restart server whenever any change is made in original project files .

npm install ts-node-dev -s

some more scripts are added in package.json:

“scripts”: {
“tsc”: “tsc”,
“dev”: “ts-node-dev –respawn –transpileOnly ./app/app.ts”,
“prod”: “tsc && node ./build/app.js”
},

start dev environment :

npm run dev

run server :

npm run prod