Saturday, February 13, 2021

React Components

Components are the building blocks of any React app and a typical React app will have many of these. Simply put, a component is a JavaScript class or function that optionally accepts inputs i.e., properties(props) and returns a React element that describes how a section of the UI (User Interface) should appear.

Every React component have their own structure, methods as well as APIs. They can be reusable as per your need. For better understanding, consider the entire UI as a tree. Here, the root is the starting component, and each of the other pieces becomes branches, which are further divided into sub-branches.

In ReactJS, we have mainly two types of components. They are

  1. Functional Components
  2. Class Components

 

Function Component

A function component is the simplest form of a React component. It is a simple function with a simple syntax.

MyComponent1.js

import React from "react";

function MyComponent1(props) {

  return <h1>This is Function Component </h1>;

}

export default MyComponent1;

 

We have created a function called MyComponent1 that returned h1 tag as shown above. The name of the function acts as an element, as shown below:

The Component MyComponent1 is used as an Html tag, i.e., < MyComponent1 /> and same is exported using export.

Let us now use this component in index.js file as shown below:

app.js

import MyComponent1 from "./MyComponent1";

function App() {

  return (

    <div className="App">

      <MyComponent1 />

    </div>

  );

}

export default App;

Here is the output in the browser:


Class as Component

Class components are more complex than functional components. It requires you to extend from React. Component and create a render function which returns a React element. Here is a ReactJS example that uses a class as a component.

MyComponent2.js

import React from "react";

class MyComponent2 extends React.Component {

  render() {

    return <h1>This is Class Component </h1>;

  }

}

export default MyComponent2;


The Component MyComponent2 is used as an Html tag, i.e., < MyComponent2 /> and same is exported using export. We can use MyComponent2 component in App.js file as follows:

App.js

import MyComponent1 from "./MyComponent1";

import MyComponent2 from "./MyComponent2";

function App() {

  return (

    <div className="App">

      <MyComponent1 />

      <MyComponent2 />

    </div>

  );

}

export default App;

The Component MyComponent2 is used as an Html tag i.e., < MyComponent2 /> 

Here is the output of the same.


Friday, February 12, 2021

React JSX

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. But instead of using regular JavaScript, React code should be written in something called JSX. 

Let us see a sample JSX code:  

const element = <h1>This is sample JSX</h1>; 


JSX (JavaScript Extension), is a React extension which allows writing JavaScript code that looks like HTML. In other words, JSX is an HTML-like syntax used by React that extends ECMAScript so that HTML-like syntax can co-exist with JavaScript/React code. The syntax is used by preprocessors (i.e., transpilers like babel) to transform HTML-like syntax into standard JavaScript objects that a JavaScript engine will parse. 

const element = React.createElement(
  "h1",
  null,
  "This is sample JSX"
);

JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the same file where you write JavaScript code, then preprocessor will transform these expressions into actual JavaScript code. Just like XML/HTML, JSX tags have a tag name, attributes, and children.


Why JSX?

  • It is faster than normal JavaScript as it performs optimizations while translating to regular JavaScript.
  • It makes it easier for us to create templates.
  • Instead of separating the markup and logic in separated files, React uses components for this purpose. We will learn about components in detail in further articles.


Using JavaScript expressions in JSX

In React we are allowed to use normal JavaScript expressions with JSX. To embed any JavaScript expression in a piece of code written in JSX we will have to wrap that expression in curly braces {}. 

Consider the below program, written in the app.js file:  

const name = "Learner";

function App() {
  return (
    <div className="App">
      <h1>Hello {name}, Welcome to Beta-Labs.</h1>
    </div>
  );
}
export default App;

Output:   


In the above program we have embedded the javascript expression const name = “Learner”; in our JSX code. We embed the use of any JavaScript expression in JSX by wrapping them in curly braces except if-else statements. But we can use conditional statements instead of if-else statements in JSX. Below is the example where conditional expressing is embedded in JSX:  


import React from 'react';
const i = 1;
const element = <h1>{i == 1 ? "Hello World!" : "False!"} </h1>;

function App() {
  return <div className="App">{element}</div>;
}
export default App;

Output: 

In the above example, the variable i is checked if for the value 1. As it equals 1 so the string ‘Hello World!’ is returned to the JSX code. If we modify the value of the variable i then the string ‘False’ will be returned.

 

Wrapping elements or Children in JSX

Consider a situation where you want to render multiple tags at a time. To do this we need to wrap all of this tag under a parent tag and then render this parent element to the HTML. All the sub-tags are called child tags or children of this parent element. 

Notice in the below example how we have wrapped ol, and li tags under a single div element and rendered them to HTML: 

import React from "react";

const element = (
  <ul>
    <li>HTML5</li>
    <li>Css3</li>
    <li>JavaScript</li>
    <li>MongoDB</li>
    <li>ReactJS</li>
  </ul>
);

function App() {
  return (
    <div className="App">
      <h1>At Beta Labs You will Learn:</h1>
      {element}
    </div>
  );
}
export default App;


Output: 


JSX Styling

React always recommends to use inline styles. To set inline styles, you need to use camelCase syntax. React automatically allows appending px after the number value on specific elements. The following example shows how to use styling in the element. 

Example

import React from "react";

const cssStyle = {
  fontSize: "24px",
  color: "white",
  backgroundColor: "black",
  padding: "10px",
  width: "500px",
  textAlign: "center",
  borderRadius: "10px",
};
function App() {
  return (
    <div className="App">
      <h2 style={cssStyle}>Beta-labs-Lets Code Together</h2>
    </div>
  );
}
export default App;

Output:


JSX Comments

JSX allows us to use comments that begin with /* and ends with */ and wrapping them in curly braces {} just like in the case of JSX expressions. Below example shows how to use comments in JSX. 

Example

import React from "react";
function App() {
  return (
    <div className="App">
      <h1>Hello from Beta-Labs</h1>
      {/* This is a comment in JSX */}
    </div>
  );
}
export default App;

  

Wednesday, February 10, 2021

Create React App & Folder Structure

In this Article, you will learn how to create a simple React app.

Prerequisites

1.    Install Node.js and NPM

2.    Install Visual Studio Code

Create React app

1.    We will use create-React-app NPX tool to create a simple React app.

2.    Open Node.js command prompt.

3.    Navigate to the respective folder, where you want to create React app.

4.    Type the command given below in a console to install create-React-app using NPX tool.

npx create-react-app myblog

5.    Navigate to the myblog folder.

6.    Type the command code . in a console to open the app in Visual Studio code.

7.    React app will have the folder structure given below.



8.    Type the command given below in a console to launch React app in the Browser.

npm start


In the previous section, you learned how to install and create a project in React. Now, whenever we create a React project, it automatically creates a lot of files and folders. So, in this article, I am going to explain what these files and folders are.

When we create a React project, our application's structure looks like this.

node_modules

The node_modules folder holds all the dependencies and sub-dependencies of our project. We only had React, React DOM and React scripts but React scripts have a lot of other dependencies which are present inside this folder.

Public folder

Basically, this folder contains 3 files as we have seen.

  • favicon.ico - it is an icon file which contains an icon which displays on the browser.
  • index.html - it is an important file. Due to this file, the public folder, known as “root folder”, gets served by the web server in the end. Index.html is a single HTML page present in this project.
  • manifest.json - this file contains a lot of information related to our application like short_name, name, icons, start_url, display etc. We can also define other metadata about our application.

src folder

This folder contains actual source code for developers. This is the place where our React application is present. We can create our own subdirectory inside this directory. For faster rebuilds, files inside only this folder are processed by Webpack. However, this folder already contains the following files. 

  • App.css - this file gives some CSS classes or we can say some styling which is used by App.js file.
  • App.js - App.js is a sample React component called “App” which we get for free when creating a new app.
  • App.test.js - this is the test file which basically allows us to create the unit tests for different units or we can say for different components.
  • index.css - it stores the base styling for our application.
  • index.js - index.js stores our main Render call from ReactDOM (more on that later). It imports our App.js component that we start with and tells React where to render it (remember that div with an id of root?).
  • logo.svg this is Scalable Vector Graphics file which contains the logo of Reactjs. By this file, we are able to see ReactJS logo on the browser.
  • registerServiceWorker.js - as its name applies, it is important for registering a service which is generated automatically and creates Progressive Web Apps which are necessary for mobile React Native apps.

Package.json

It is a standard file found in every project. It contains the information like the name of project, versions, dependencies etc. Whenever we install a third party library, it automatically gets registered into this file.

Example - content of package.json file

A point to be remembered at the time of working with React applications is that, for the project to build, these files must exist with exact filenames.

  1. public/index.html is the page template;
  2. src/index.js is the JavaScript entry point.

We can delete or rename the other files.