Learn React.JS in 10 Minutes

ReactJS is a popular JavaScript library used extensively for building user interfaces developed by Facebook. It is a JavaScript view-based framework, which uses HTML language. It supports one-way binding which essentially means that it does not have a mechanism to allow HTML to change the components. HTML can only raise events that the components respond to.

In ReactJS, ‘state’ is the interface between back-end data and UI elements in the front end. State helps to keep the data of different components in sync to ensure that each state update will render all relevant components. To simplify, state is the medium to communicate between different components.

In this blog, I will touch upon state management, automatic back-end data refresh (no F5) and retrieving data from API and rendering the same.

Pre-requisite – Please ensure that you have installed Node.js (latest package from https://nodejs.org/en/).

To create your first ReactJs project, we will use the following command in the selected directory. This will create new project under firstreactjsapp directory.

npm init react-app firstreactjsapp
Navigate to the newly created folder, and you will see public and src directories.

To update content, go to App.js file and replace App with following code:
function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1>First ReactJS Application</h1> </header> </div> ); }
Run ReactJS application using following command and you will see below output. (prefer Chrome browser)
npm start

Interacting with API. We will use Axios, is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js.

npm i axios

Accessing API ( lets get some available online api’s from (https://jsonplaceholder.typicode.com).

Creating ToDo list grid.

Copy following code and past it in the App.js:

import React from 'react';
 import axios from 'axios'; // Reference axios for accessing API’s
 export default class PersonList extends React.Component {
 state = {
 todos: [],
 onetime:true
 }
 fetchNews(me)
 {
 if (me.state.onetime) // load data onetime
 {
 axios.get('https://jsonplaceholder.typicode.com/todos') // retreiving from backend
 .then(res => {
 var todos = []
 todos = res.data.slice(0,10); // lets fetch only 10 records
 // lets randomly update the status of first record using backgroudn thread without refershing the page or pressing F5.
 todos[0].completed = todos[0].completed==="true" ? "false" : "true";
 me.setState({ todos });
 var onetime = false;
 me.setState({ onetime }); // changing state.
 })
 }
 else
 {
 var todos = []
 todos = me.state.todos;
 todos[0].completed = todos[0].completed==="true" ? "false" : "true";
 me.setState({todos });
 }
 }
 componentWillMount() {
 if (this.state.onetime)
 {
 this.fetchNews(this);
 }
 this.interval = setInterval(this.fetchNews, 500,this); // refresh
 }
 render() { // rendering
 return (
 <ul>
 <table border="1">
 <tr><td>Id</td><td>UserID</td><td>Title</td><td>Status</td></tr>
 { this.state.todos.map(todo =>
 <tr>
 <td> <a href="/">{todo.id}</a></td>
 <td> {todo.userId}</td>
 <td> {todo.title}</td>
 <td> {todo.completed}</td>
 </tr>
 )
 }
 </table>
 </ul>
 )
 }
 }
Run React application using the following command and you will see the below output. (prefer Chrome browser)
npm start

Did you find this blog useful? Send your comments to info@trigent.com.

String extensions using LINQ

For the question, `The class System.String is sealed and therefore you cannot use it for overriding or inheritance?’ There is  a Yes and a No answer. Yes! you can extend existing types by using extension methods. Extension methods, naturally, can only access the public interface of the type  or you can write your own extension method for the string operations.

In this blog, I am going to show you how to create new operations to  existing string objects. The following code explains typical string operations that we come across in our day-t0-day coding, to get the Left , Right, Shorten operations. It does look very technical, i.e. the string manipulations, the condition checks. However,  this is the solution from a technical point of view.

using System;

namespace My.Extensions
{
public static class StringExtensions
{
public static string Left(this string s, int count) {
if(count > s.Length) {
return s;
}

return s.Substring(0, count);
}

public static string Right(this string s, int count) {
if(s.Length <= count) {
return s;
}

return s.Substring(s.Length – count, count);
}

public static string Shorten(this string s, int count) {
if(s.Length < count) {
return String.Empty;
}

return s.Substring(0, s.Length – count);
}
}
}

There is a way to implement that functionality in a descriptive way which makes it look more aesthetic. The key is to understand a string as a sequence of characters. Let’s try to rewrite the extension methods using LINQ:

The code is shorter; it looks more precise. The core part of the methods is extremely descriptive. The methods meet respective purpose by taking or skipping a certain number of characters of the input string.

using System.Collections.Generic;
 using System.Linq;

namespace My.Extensions
{
public static class StringExtensions
{
public static string Left(this string characters, int number) {
return characters.Take(number).AsString();
}

public static string Right(this string characters, int number) {
return characters.Skip(characters.Length – number).AsString();
}

public static string Shorten(this string characters, int number) {
return characters.Take(characters.Length – number).AsString();
}
}

public static class EnumerableExtensions
{
public static string AsString(this IEnumerable<char> characters) {
return new string(characters.ToArray());
}
}
}

Unit testing the original implementation as well as the one developed here:

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace My.Extensions.Tests
{
[TestClass]
public class MyExtensionsSpecifications
{
private const string Abcdefghij = “abcdefghij”;

[TestMethod]
public void The_first_5_characters_of_abcdefghij_are_abcde() {
Assert.AreEqual(“abcde”, Abcdefghij.Left(5));
}

[TestMethod]
public void The_first_50_characters_of_abcdefghij_are_abcdefghij() {
Assert.AreEqual(Abcdefghij, Abcdefghij.Left(50));
}

[TestMethod]
public void The_last_3_characters_of_abcdefghij_are_hij() {
Assert.AreEqual(“hij”, Abcdefghij.Right(3));
}

[TestMethod]
public void The_last_20_characters_of_abcdefghij_are_abcdefghij() {
Assert.AreEqual(Abcdefghij, Abcdefghij.Right(20));
}

[TestMethod]
public void abcdefghij_shortened_by_4_characters_is_abcdef() {
Assert.AreEqual(“abcdef”, Abcdefghij.Shorten(4));
}

[TestMethod]
public void abcdefghij_shortened_by_12_characters_is_an_empty_string() {
Assert.AreEqual(string.Empty, Abcdefghij.Shorten(12));
}
}
}