Michio JP

Michio JP

1548317107

Getting started with Reason React and BuckleScript

This tutorial will introduce OCaml, Reason React, and BuckleScript, and explain their relevance. To wrap things up, we will take a look at a demo project built with ReasonReact. ReasonReact is a simpler and much safer way to build React components in Reason, and with the help of BuckleScript, we can have access to a JavaScript version of all code written in Reason. More about this later in the tutorial.

Introduction

The importance of productivity in programming is very crucial to the success of any Software Engineer in particular, as it facilitates an implementation of features on time, working successfully with a very large team, and my favorite, being able to sleep at night without getting worried about the new code you just merged with the master branch.

There are many competing programming paradigms, each with their own approaches to application flow, syntax and other conventions.

Easy access to relevant tools, you will agree with me, will go a long way to not only make you productive as a Software Engineer but also enhance your current skill set.

The semantics

OCaml is an expressive and dynamic strictly typed general purpose programming language. It lays more emphasis on expressiveness and safety. Its been around for a while (over 20 years) now but its popularity has been on the lower side due to its small community. Most notable companies make use of it to minimize errors and improve speed. Facebook, for example, uses OCaml to developed type checkers like Hack for PHP and Flow for JavaScript.

The syntax

Reason on the other hand is not another programming language per say, but a new syntax and toolchain powered by OCaml. It provides a familiar, usable interface intended to make interoperation with JavaScript and adoption by JavaScript developers easier. In view of this, ReactReason was introduced to give JavaScript developers, especially the ReactJS community, to leverage the greater type system of Reason.

The compiler

BuckleScript compiles OCaml/Reason code down to plain JavaScript that can easily be shipped to virtually any browser in the world. One of the benefits of BuckleScript is the amazing speed at which it compiles down to human-readable JavaScript.

Getting started

Run the command below to globally install BuckleScript on your machine:

 $ npm install -g bs-platform 

Once the installation process is completed, we will now fully have access to the bsbcommand that would be used to easily initialize a quick Reason project.

Creating a basic project

By now, you should have BuckleScript installed successfully. To see it in action, let’s generate a lightweight Reason project template with:

 $ bsb -init reason-sample-project -theme basic-reason 

The boilerplate should have a similar project structure as shown here:

Next, run a command to build the project from the terminal in the root directory of the project:

 $ npm run build 

Did you notice a new file Demo.bs.js that was quickly generated for the project? The compiled version of Reason to JavaScript is housed by this file. Feel free to check and view it.

Lastly, type node src/demo.bs.js in your terminal to run the JavaScript output.

This will log a message Hello, BuckleScript and Reason! to the console. Now open the project with your favorite text editor and make a change to the message within the Js.log()method located in ./src/Demo.re , then proceed to build and see your changes.

Concepts overview

Reason introduces a new way of writing OCaml and still retains access to the beauty of static types. Let’s take a quick look at some basic concepts of Reason, such as variants, functions, and pattern-matching since we’ll be using it to build a demo.

Variants in Reason are data types and structures. It can be used to define sets of symbols and data structures. You can read more about variant here.

 /* ./src/Demo.re */ type animal = Cat(string) | Dog(string); 

We have the type of an animal which can either be a Cat or Dog and both will only accept a string as an argument.

Functions in Reason are declared with an arrow and a return expression. Declare one as shown here:

 /* ./src/Demo.re */ let speak = (animal) => switch (animal) { | Cat(name) => name ++ " says: meow" | Dog(name) => name ++ " says: woof" }; 

Here, what we have done is to declare a function speak and passed an argument using the type that was declared earlier. Within it, we used a switch expression and checked for every possible case of the animal variant, this is referred to as pattern-matching in Reason. One of the advantages of pattern-matching is that it is very exhaustive, you will get a warning in the console if you did not check for both cases.

Furthermore, for each of the variants, we passed a variable name and later concatenated it with a statement representing what we want each of the animal to say.

Now we can simply call the function and passed any of the types of animal into it:

 /* ./src/Demo.re */ Js.log(speak(Dog("Cooper"))); Js.log(speak(Cat("Buddy"))); 

Navigate to ./src/Demo.bs.js to see the equivalent JavaScript version of the functions declared in Reason above as compiled by BuckleScript.

Let’s build a todo app with Reason

To get a better grasp of the concept of building web applications with Reason, we’ll use Reason-scripts to build a simple todo list application. This will be a familiar experience for ReactJS users that are conversant with create-react-app. While building this app we will get a much better introduction to the syntax and type system of Reason.

Prerequisites

A basic understanding of React will be of great assistance with this tutorial. Before we get started, we need to install some required set of tools:

  1. We will be using create-react-app to create a boilerplate for this project. Run this command from your terminal to install it globally on your machine:
 $ npm i -g create-react-app 
  1. Finally head over to editor setup to get the Reason plugin for your favorite editor as this will help facilitate the development process.

Creating the Reason React project

We’ll create our project using the create-react-app command. Navigate to your project folder and run a command that will create a project named reason-bucklescript-todo:

 $ create-react-app reason-bucklescript-todo --scripts-version reason-scripts 

Next, change directory into the newly created project and first, run npm link bs-platformand start the application with npm start or yarn start:

ReasonReact components

Similar to a ReactJS application, ReasonReact supports the use of components to structure an application. By default, the create-react-app already generated a basic App component for us. Navigate to ./src/App.re and edit as follow:

 /* ./src/App.re */ [%bs.raw {|require('./App.css')|}]; [@bs.module] external logo : string = "./logo.svg"; let component = ReasonReact.statelessComponent("App"); let make = (~message, _children) => { ...component, render: _self => <div className="App"> <div className="App-header"> <img src=logo className="App-logo" alt="logo" /> <h2> {ReasonReact.string(message)} </h2> </div> <div className="App-intro"> <Todo /> </div> </div>, }; 

Since the structure of the file above is similar to what we would have for other components, let’s take a quick look at some of its parts.

First, we required a stylesheet with [%bs.raw {|require('./App.css')|}]; at the top of the file. BuckleScript allows us to include some raw JavaScript code by using [%bs.raw ] and wrapping the JavaScript code with {| |}.

Defining a component

Next, a component can either be stateless or stateful. In ReasonReact, there are different ways of defining them:

  1. Stateless components: defined as ReasonReact.statelessComponent("componentName")
  2. Stateful components: defined as ReasonReact.reducerComponent("componentName")

Furthermore, we declared a make function which takes in two different parameters. The first parameter has a symbol ~ indicating that it was passed into the App component as a propsand the second parameter has _, this is a more explicit way of showing that the parameter isn’t used and ignored.

In addition, the …component spread operator indicated that the make function declared is building upon the component that was just defined. We also declare a render function with a single argument _self that is not used at the moment.

Rendering a string in ReasonReact is a little bit different than what we have in ReactJS, here you will have to wrap the string with a function named ReasonReact.string().

Finally, we included and rendered a component <Todo /> without importing any file, interesting right? In ReasonReact, every component is a module and doesn’t need to be imported before it can be used in another module. We’ll create this Todo component in a bit.

Creating components

For a better folder structure, we will group all new components in the same directory that will be named components. For BuckleScript to detect the Reason files and compile them easily to JavaScript we’ll need to edit the BuckleScript configuration file. Open ./bsconfig.json and add a new source as shown below:

    // ./bsconfig.json
{
  "name": "reason-scripts",
  "sources": [
    "src",
    "src/components" // Add this line
  ],
  ...
}

With the configuration above, any .re file created within the components directory will be compiled down to JavaScript. Before we start creating the required files, locate the srcdirectory and create another directory named components inside of it.

Set up the todo component

First, let’s create a new file, TodoType.re in the components directory and paste the code below in it. This will define the data structure for the list of Todo items:

 /* ./src/components/TodoType.re / type item = { id: int, title: string, completed: bool, };

As pointed out earlier, every file in ReasonReact is a module and all the things defined at the top level of the file using the keywords let, type, and module are exposed to be used from other files. So in other components we will need to reference the TodoType component that we just created.

Todo component

Navigate to the src/components directory and create a new file Todo.re within it. Open the new file and paste in this code:

 / ./src/components/Todo.re / type state = { items: list(TodoType.item), inputText: string, }; type action = | InputText(string) | Toggle(int) | RemoveItem(int) | Submit; let component = ReasonReact.reducerComponent(“Todo”); let make = children => { let handleSubmit = state => { let newId: int = List.length(state.items); let newItem: TodoType.item = { id: newId, title: state.inputText, completed: false, }; let newList = [newItem, …state.items]; ReasonReact.Update({items: newList, inputText: “”}); }; { …component, initialState: () => { items: [{id: 0, title: “Fix more bugs”, completed: false}], inputText: “”, }, reducer: action => switch (action) { | InputText(newText) => ( state => ReasonReact.Update({…state, inputText: newText}) ) | Toggle(id) => (state => ReasonReact.Update({ …state, items: List.map((item: TodoType.item) => item.id == id ? { …item, TodoType.completed: ! TodoType.(item.completed), } : item, state.items, ), }) ) | RemoveItem(id) => ( state => ReasonReact.Update({ …state, items: List.filter( (item: TodoType.item) => item.id !== id, state.items, ), }) ) | Submit => (state => handleSubmit(state)) }, render: self => { let {items, inputText} = self.state; <div className=“app”> <div className=“app-header”> <div className=“title”> {ReasonReact.string(“Todo List”)} </div> </div> <Input submit=( => self.send(Submit)) value=inputText onInputText=(text => self.send(InputText(text))) /> <div className=“list”> ( ReasonReact.array( Array.of_list( List.map( (item: TodoType.item) => <Item key=(string_of_int(item.id)) item onRemove=(id => self.send(RemoveItem(id))) onToggle=(id => self.send(Toggle(id))) />, items, ), ), ) ) </div> </div>; }, }; };

The file above is an example of a stateful component in ReasonReact. And within it, first, we defined the state for the component and a set of actions that will be required to mutate the state of each item. And within the make function of the component, we defined a function named handleSubmit to handle the addition of new item and then update the existing todo list once created.

Next, we defined the initialState of the todo items and added a reducer method which takes the action as a parameter and used pattern-matching on the action type, returning a ReasonReact.Update which contains the new state.

Input component

This component will be used to add an item to a to-do list and therefore can be maintained as a stateless component since its main function is to emit an event that will trigger the handleSubmit function within the Todo component. Create this file within ./src/componentsand name it Input.re. Once you are done, paste the content below in it:

 / ./src/components/Input.re / let component = ReasonReact.statelessComponent(“Input”); let make = (~value, ~onInputText, ~submit, _children) => { …component, render: self => <div className=“input”> <input value placeholder=“Enter item and click add” onChange=( event => onInputText( ReactDOMRe.domElementToObj(ReactEventRe.Form.target(event))##value, ) ) /> <button onClick=( => submit())> (ReasonReact.string(“Add”)) </button> </div>, };

Item component

Finally, we will define a stateless component for rendering the items as they are being added. To do this, create a new file named Item.re within ./src/components directory and paste the code below:

 / ./src/components/Item.re / let component = ReasonReact.statelessComponent(“Item”); let make = (~item: TodoType.item, ~onRemove, ~onToggle, _children) => { …component, render: self => <div className=“item”> <input type=“checkbox” checked=item.completed onChange=( => onToggle(item.id)) /> <p> {ReasonReact.string(item.title)} </p> <button onClick=( => onRemove(item.id))> {ReasonReact.string(“Remove”)} </button> </div>, };

Stylesheet

Open ./src/App.css and paste the code below to add some styling to the application:

    / ./src/App.css */

  .App {
    text-align: center;
  }
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
    height: 80px;
  }
  .App-intro {
    font-size: large;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
  }
  .App-header {
    background-color: #222;
    height: 150px;
    padding: 20px;
    color: white;
  }
  .app {
    width: 500px;
    margin: 10px;
  }
  .app-header {
    margin: 10px;
  }
  .title {
    font-size: 25px;
    font-weight: 500;
  }
  .input {
    display: flex;
    justify-content: flex-start;
  }
  .input input {
    width: 80%;
    height: 30px;
    padding: 5px;
    font-size: medium;
  }
  .input button {
    background-color: green;
    color: white;
    font-size: medium;
    width: 30%;
    margin-left: 20px;
  }
  .list {
    margin-top: 25px;
  }
  .item {
    display: flex;
    border: #f5f5f5 2px solid;
    align-items: center;
    height: 30px;
    padding: 10px;
    margin-top: 5px;
    font-size: larger;
  }
  .item p {
    text-align: left;
    margin: auto;
  }
  .item button {
    padding: 10px;
    background-color: grey;
    font-size: 14px;
    opacity: 0.95;
  }
  @keyframes App-logo-spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

And that is it. You should have a functional todo app by now

Conclusion

I hope this very simple application was helpful enough to increase your enthusiasm for exploring Reason and its syntax.

We barely scratched the surface of some awesome features in Reason and BuckleScript. You can visit the documentation to learn more about it.

The source code for the todo app can be found here on GitHub.

#reactjs #javascript

What is GEEK

Buddha Community

Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Mathew Rini

1615544450

How to Select and Hire the Best React JS and React Native Developers?

Since March 2020 reached 556 million monthly downloads have increased, It shows that React JS has been steadily growing. React.js also provides a desirable amount of pliancy and efficiency for developing innovative solutions with interactive user interfaces. It’s no surprise that an increasing number of businesses are adopting this technology. How do you select and recruit React.js developers who will propel your project forward? How much does a React developer make? We’ll bring you here all the details you need.

What is React.js?

Facebook built and maintains React.js, an open-source JavaScript library for designing development tools. React.js is used to create single-page applications (SPAs) that can be used in conjunction with React Native to develop native cross-platform apps.

React vs React Native

  • React Native is a platform that uses a collection of mobile-specific components provided by the React kit, while React.js is a JavaScript-based library.
  • React.js and React Native have similar syntax and workflows, but their implementation is quite different.
  • React Native is designed to create native mobile apps that are distinct from those created in Objective-C or Java. React, on the other hand, can be used to develop web apps, hybrid and mobile & desktop applications.
  • React Native, in essence, takes the same conceptual UI cornerstones as standard iOS and Android apps and assembles them using React.js syntax to create a rich mobile experience.

What is the Average React Developer Salary?

In the United States, the average React developer salary is $94,205 a year, or $30-$48 per hour, This is one of the highest among JavaScript developers. The starting salary for junior React.js developers is $60,510 per year, rising to $112,480 for senior roles.

* React.js Developer Salary by Country

  • United States- $120,000
  • Canada - $110,000
  • United Kingdom - $71,820
  • The Netherlands $49,095
  • Spain - $35,423.00
  • France - $44,284
  • Ukraine - $28,990
  • India - $9,843
  • Sweden - $55,173
  • Singapore - $43,801

In context of software developer wage rates, the United States continues to lead. In high-tech cities like San Francisco and New York, average React developer salaries will hit $98K and $114per year, overall.

However, the need for React.js and React Native developer is outpacing local labour markets. As a result, many businesses have difficulty locating and recruiting them locally.

It’s no surprise that for US and European companies looking for professional and budget engineers, offshore regions like India are becoming especially interesting. This area has a large number of app development companies, a good rate with quality, and a good pool of React.js front-end developers.

As per Linkedin, the country’s IT industry employs over a million React specialists. Furthermore, for the same or less money than hiring a React.js programmer locally, you may recruit someone with much expertise and a broader technical stack.

How to Hire React.js Developers?

  • Conduct thorough candidate research, including portfolios and areas of expertise.
  • Before you sit down with your interviewing panel, do some homework.
  • Examine the final outcome and hire the ideal candidate.

Why is React.js Popular?

React is a very strong framework. React.js makes use of a powerful synchronization method known as Virtual DOM, which compares the current page architecture to the expected page architecture and updates the appropriate components as long as the user input.

React is scalable. it utilises a single language, For server-client side, and mobile platform.

React is steady.React.js is completely adaptable, which means it seldom, if ever, updates the user interface. This enables legacy projects to be updated to the most new edition of React.js without having to change the codebase or make a few small changes.

React is adaptable. It can be conveniently paired with various state administrators (e.g., Redux, Flux, Alt or Reflux) and can be used to implement a number of architectural patterns.

Is there a market for React.js programmers?
The need for React.js developers is rising at an unparalleled rate. React.js is currently used by over one million websites around the world. React is used by Fortune 400+ businesses and popular companies such as Facebook, Twitter, Glassdoor and Cloudflare.

Final thoughts:

As you’ve seen, locating and Hire React js Developer and Hire React Native developer is a difficult challenge. You will have less challenges selecting the correct fit for your projects if you identify growing offshore locations (e.g. India) and take into consideration the details above.

If you want to make this process easier, You can visit our website for more, or else to write a email, we’ll help you to finding top rated React.js and React Native developers easier and with strives to create this operation

#hire-react-js-developer #hire-react-native-developer #react #react-native #react-js #hire-react-js-programmer

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

Madelyn  Frami

Madelyn Frami

1603212060

Beginners Guide to Get Started with Unit Testing in React Native

Automated tests give you confidence in the piece of code you write. Sometimes we write code that works locally then push to production. However, changes made breaks entirely different parts of the project.

Someone else on your team might have written these parts of the project, but your changes caused conflicts. Testing prevents this.

There are different types of tests: unit tests, integration tests, functional tests, end-to-end tests, and many more.

What is unit testing?

Using a car as an analogy, we all know that a car comprises of different components (Unless you live in a tree 🤪). These components comprise wheels, an engine, headlights, and taillights, etc.

Unit tests basically ensure each individual component performs as expected. Looking at our car analogy, to ensure our wheel is perfectly round we rotate it by exerting external force, same way we write unit tests to ensure individual components of our source code (software) function as they ought to.

In this article, we will be looking at the basic principles of unit tests with a simple react-native Button component.

Let’s go ahead to create a Button component.

import React from 'react';
import {Pressable, Text, View, StyleSheet} from 'react-native';

const Button = ({onPress, title, isLoading, transparent}) => {
  return (
    <Pressable
      onPress={() => {
        if (!isLoading) {
          return onPress();
        }
      }}>
      <View style={transparent ? styles.transparentBtn : styles.btn}>
        <Text style={transparent ? styles.transparentTitle : styles.title}>
          {isLoading ? 'Loading...' : title}
        </Text>
      </View>
    </Pressable>
  );
};

const styles = StyleSheet.create({
  btn: {
    width: '100%',
    height: 50,
    backgroundColor: '#74B3CE',
    alignItems: 'center',
    justifyContent: 'center',
    marginVertical: 10,
    borderRadius: 4,
  },
  transparentBtn: {
    width: '100%',
    height: 50,
    backgroundColor: 'transparent',
    alignItems: 'center',
    justifyContent: 'center',
    marginVertical: 10,
  },
  title: {
    color: 'white',
    fontSize: 16,
  },
  transparentTitle: {
    color: '#74B3CE',
  },
});

export default Button;

#react-native #unit-testing #test-automation #introduction #react #getting-started #jest #enzyme