The purpose of arrow functions in React classes

Arrow functions are an essential part of every React class. However, members
of React classes can be non-arrow, too. Lets take a look at the following React app:


import React, { Component } from 'react';
import './App.css';

class App extends Component {

  state = {
    halloworld: 'halloworld'
  }

  sayHalloWorld() {
    alert(this.state.halloworld);    
  }

  sayHalloWorldArrow = () => {
    alert(this.state.halloworld);
  }

  render() {
    return (
      <div className="App">
        <button onClick={this.sayHalloWorld}>Click Me No Bind</button>
        <button onClick={this.sayHalloWorld.bind(this)}>Click Me With Bind</button>
        <button onClick={this.sayHalloWorldArrow}>Click Me Arrow</button>
      </div>
    );
  }
}

export default App;

This app shows three buttons, each shows an alert box “halloworld” when being clicked. Wait, each of them?
No, the first button, in fact, creates an error which says that this.state.halloworld is undefined.

Why is that?

To understand this, it is essential to understand what happens when React classes are instantiated. Have you ever noticed, that you never ever instantiate any of your React classes? I guess so! The reason is, that the React framework instantiates your classes, not you.

Lets create a “fake” React class and instantiate this by ourselves:


class fakeReactClass {

    state = {
        halloworld: 'Hallo World'
    }

    sayHalloWorld() {
        console.log( this.state.halloworld );
    }

    render() {
        return this.sayHalloWorld;        
    }
}

// here we act as the React framework and instantiate our React class
const frc = new fakeReactClass();
frc.render()(); // this executes the reference to this.sayHalloWorld

Note: You need Babel 7 to transpile this ES2015 to older JavaScript in order to run it.

So, what happens when we run this code? We get an error! TypeError: Cannot read property ‘state’ of undefined.
Why is that? The reason is that the this-Keyword of the function sayHalloWorld looses its reference to class fakeReactClass, when you call sayHalloWorld(). It now points to nowhere, to undefined.

Therefore, it is essantial to explicitly return a reference of sayHalloWorld in which the this-Keyword is forced to point to fakeReactClass:


class fakeReactClass {

    state = {
        halloworld: 'Hallo World'
    }

    sayHalloWorld() {
        console.log( this.state.halloworld );
    }

    render() {
        return this.sayHalloWorld.bind(this);
    }
}

// here we act as the React framework and instantiate our React class
const frc = new fakeReactClass();
frc.render()(); // this executes the reference to this.sayHalloWorld 

In contrast to the first example, here we return a reference to this.sayHalloWorld
that is explicitly bound to the fakeReactClass. This can be done with the bind() function
that is part of every function object in JavaScript.

So what about arrow functions then? Not that only their syntax may appear more handy
to many developers, there is a significant difference to ordinary function: the this-Keyword inside arrow functions sticks to the lexical context no matther
in what context the arrow function will be executed later:

class fakeReactClass {

    state = {
        halloworld: 'Hallo World'
    }

    sayHalloWorldArrow = () => {
        console.log( this.state.halloworld );
    }

    render() {
        return this.sayHalloWorldArrow;
    }
}

// here we act as the React framework and instantiate our React class
const frc = new fakeReactClass();
frc.render()(); // this executes the reference to this.sayHalloWorldArrow

To sum it up, the arrow function is used as a shorter version for all the bind()
calls that ordinary functions in JavaScript entail.

Tree Structure in React using Recursive Components

Trees are common to represent nested folder structures, diagrams, hierarchies, friendship structures and so on.

Lets assume we want to illustrate the following folder structure in a React Web App:

jan/
├── coding
│   ├── backend
│   └── frontend
└── music
     ├── electro
     ├── hiphop
     └── reggae

This could be represented as a JavaScript object like:

    tree: {
      name: 'jan',
      subnodes: [
        { 
          name: 'music', 
          subnodes: [
            { name: 'electro', subnodes: [] },
            { name: 'hiphop', subnodes: [] },
            { name: 'reggae', subnodes: [] },
          ]
        },
        { 
          name: 'coding',
          subnodes: [
            { name: 'frontend' , subnodes: [] },
            { name: 'backend' , subnodes: [] }
          ]
        }
      ]
    }

The question now is, how can we represent this structure in a React App. I suggest we use
a nested, unordered list and we would come up with something like:


<ul>
	<li>jan
		<ul>
			<li>music
			<ul>
				<li>electro</li>
			</ul>
			<ul>
				<li>hiphop</li></ul>
			<ul>
				<li>reggae</li>
			</ul>
			</li>
		</ul>
		<ul>
			<li>coding
				<ul>
					<li>frontend</li>
				</ul>
				<ul>
					<li>backend</li>
				</ul>
			</li>
		</ul>
	</li>
</ul>

Each leaf of the tree itself can contain another leaf. Or in other words,
each list item can contain another list. This recursive structure can be
represented like this:


import React, { Component } from 'react'

export default class FolderTree extends Component {
  
  render() {
    return (
      <ul>
        <li>{this.props.node.name}
	        this.props.node.subnodes.map((n) => {
	            return <FolderTree node={n} />
	        })
        </li>
      </ul>
    )
  }
}

Eventually, the App component looks like this:


import React, { Component } from 'react';
import FolderTree from './FolderTree';
import './App.css';

class App extends Component {
  
  state = {
    tree: {
      name: 'jan',
      subnodes: [
        { 
          name: 'music', 
          subnodes: [
            { name: 'electro', subnodes: [] },
            { name: 'hiphop', subnodes: [] },
            { name: 'reggae', subnodes: [] },
          ]
        },
        { 
          name: 'coding',
          subnodes: [
            { name: 'frontend' , subnodes: [] },
            { name: 'backend' , subnodes: [] }
          ]
        }
      ]
    }
  }
  
  render() {
    return (
      <div className="App">
        <FolderTree node={this.state.tree} />
      </div>
    );
  }
}

export default App;

Most useful Linux Commands Overview Part 2: Searching for Files

Command Description Example
find searches for files by its name, date, file size etc. find / -name foo.txt -type f -print # full command
find / -name foo.txt -type f # -print isn’t necessary
find / -name foo.txt # don’t have to specify “type==file”
find . -name foo.txt # search under the current dir
find . -name “foo.*” # wildcard
find . -name “*.txt” # wildcard
find /users/al -name Cookbook -type d # search ‘/users/al’ dir
grep searches text in files grep ‘word’ filename
grep ‘word’ file1 file2 file3
grep ‘string1 string2’ filename
cat otherfile | grep ‘something’
command | grep ‘something’
command option1 | grep ‘data’
grep –color ‘data’ fileName
locate searches for files $ locate sysctl.conf
/etc/sysctl.conf
/usr/share/man/man5/sysctl.conf.5.gz
whereis locates linux commands in the system $ whereis open
open: /bin/open /usr/share/man/man1/open.1.gz /usr/share/man/man2/open.2.gz
which locates linux commands in the system $ which ls gdb open grep
/bin/ls
/usr/bin/gdb
/bin/open
/bin/grep

Most useful Linux Commands Overview Part 1: File Management

Command Description Example
cat shows file’s content/connects multiple files to one file cat ~/.bashrc
cd changes directory cd ~/Desktop
chgrp changes a file’s group chgrp somegroupname file.txt
chmod changes a file’s access bits for user, group and others. (4 stands for “read”,
2 stands for “write”,
1 stands for “execute”, and
0 stands for “no permission.”)
chmody 754 myfile.text
chown changes a file’s owner chown someusername:somegroupname myfile.txt
cp copies files cp myfile.txt copyofmyfile.txt
inotifywait waits for changes of file attributes inotifywait changeme.txt
ln creates soft and hard links to files ln -s ~/mywebsitefolder /var/www/html/mywebsitefolder
ls shows a folder’s content ls -la /var/www/html
mkdir creates a new folder mkdir ~/Desktop/myPictures
mv moves files or changes it’s name mv myfile.txt mynewfile.txt
rename renames multiple files rename ‘s/\.html$/\.php/’ *.html More info…
rm removes files rm *.mp4
rsync synchronizes folders rsync -av /folder1 /folder2 More info…
stat gives detailed information about files stat download.tar
touch creates an empty file touch emptyfile.txt
tree shows folders and its subfolders/files as a tree tree ~/Desktop
truncate shrinks or extends a file’s size truncate -s 0 myfile.txt

JSON functionality in Postgres

In the last recent versions, Postgres got some neat JSON functionality.

take a look:

create table person ( id integer, data json );
insert into person (1, '{"name" : "Jason", "age" : "24" }');
insert into person (2, '{"name" : "Maria", "age" : "30" }');
insert into person (3, '{"name" : "Bill",
"age" : "20",
food: {
"favourite" : "cereal",
"least_favourite": "hotdog"
}');

now some select query:

select id, data->>'name' from person;
select id, data->>'food'->>'favourite' from person;