React Basics

2 minutes read

Presentational components

Definition

Presentational components are usually stateless components / components that do not manage state and are used for displaying data.
Presentational components are usually children of container components.

Characteristics of presentational components

  • presentational components are stateless
  • they receive the date to be displayed from the parent components

Container components

Definition

Container components are usually stateful components/components that manage state, components that have the responsibility of how things work.
Container components are usually parents of presentational components.

Characteristics of container components

  • usually do not have any HTML tags besides sometimes
  • usually stateful components
  • they provide data to the children components (to the presentational components)

Example of a container component


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

class PostList extends Component{

	constructor(props){
		super(props);
		
		this.state = {
			posts: []
		};
	}		
	
	
	componentDidMount(){	
		fetch('https://jsonplaceholder.typicode.com/posts')
			.then(response => response.json())
			.then(json => this.setState({posts:json}));
	}

	render(){
		
		return( 

			<div>
				{
					this.state.posts.map(post => {
						return <PostTitle postTitle={post.title}/>
					})
				}
			</div>
		);
	}
}

Example of a presentational component written as a class component


import React, { Component } from 'react';

class PostTitle extends Component{
	render(){
		return <h1>Post title: {this.props.postTitle}</h1>;	
	}
}

export default PostTitle;

Example of a presentational component written as a function component


import React from 'react';

function PostTitle(props) {
		return <h1>Post title: {props.postTitle}</h1>;		
}

export default PostTitle;

Example of a presentational component written as a function component using the arrow function


import React from 'react';

const PostTitle = (props) => {
		return <h1>Post title: {props.postTitle}</h1>;		
}

export default PostTitle;

In the end we have broken up our application into two components:

  • PostTitle which does not manage any state / stateless and is a presentational component
  • PostList which manages the state (stateful) and is a container component

React Basics React Components React State

2 minutes read

React state meaning

State in React represents the components own local state.
The state cannot be accessed and modified outside the component
and can only be used inside the component.

Adding state to a component

Until recently when React Hooks were introduced there was no way of using state with function components. The new React Hooks feature will be discussed in a different post.

For now we will consider state in relation with using it inside class components.

Example using state inside class components


import React, { Component } from 'react';

class LoginBar extends Component{

	constructor(props){
		super(props);

		this.state = {
			userType: 'basic'
		};
	}

	render(){
		return(
			<h1> Logged in as {this.props.username} type {this.state.userType}</h1>
		);
	}
}

export default LoginBar;

Initialise the state of a React component

There are 2 ways of initialising the state of a component:

  • Inside the constructor
  • Directly in the class as a class property

Initialise state inside the constructor


class LoginBar extends Component{

	constructor(props){
		super(props);

		this.state = {
			userType: 'basic'
		};
	}

	render(){
		return(
			<h1> Logged in as {this.props.username} type {this.state.userType}</h1>
		);
	}
}
export default LoginBar;

Warning: Class components should always pass props to the base class constructor.

Directly in the class as a class property


import React, { Component } from 'react';

class LoginBar extends Component{

	state = {
		userType: 'basic'
	};

	render(){
		return(
			<h1> Logged in as {this.props.username} type {this.state.userType}</h1>
		);
	}
}

export default LoginBar;

For this to work we need to enable Babel’s class properties transform as the class property syntax is not yet in the official JS spec.

Both implementations achieve the same goal, just that the second one even though relying on a proposition is a little more clean.

React Basics React Elements

3 minutes read

What are React elements?

Elements are the smallest building blocks of any React app and describe what you want to see on the screen.
In essence an element is a plain object describing a component instance or DOM node and its desired properties.

What information do React elements contain?

The elements contain only information related to:

  • type (for example Button, div)
  • its properties
  • any child elements that it contains inside it

How can you create the object representation of a DOM node / component element instance?

For manually creating the React element object representation we can use the createElement method.


React.createElement(
  type,
  [props],
  [...children]
)

The type argument can be either a DOM tag name string (such as ‘div’) or a React component type (a class or a function) or a React fragment type.

Usually you will not invoke React.createElement() directly as most of the time you will be using JSX.

The code written in JSX will be converted into using React.createElement().

Example of using React.createElement:


const element = React.createElement('div',{id:'search-button'},'Results');
Example of using React.createElement:

const element = <div id="search-button">Results</div>

What does the React createElement return?

The method return just an immutable description object with two fields:


type: (string | ReactClass)
props: Object.
For example:

{
	type: 'div',
	props: {
		children: 'Results',
		id: 'search-button'
	}
}

When does an element represent a DOM node?

When an element’s type is a string, it represents a DOM node with that tag name and with the props corresponding to its attributes. For example the object representation below is a DOM node:


{
	type: 'div',
	props: {
		className: 'highlight red',
		children: {
			type: 'b',
			props: {
				children: 'Hello React!'
			}
		}
	}
}

Basically the object above represents the object representation of the following HTML:


<div class="highlight red">
  <b>
    Hello React!
  </b>
</div>

How to create an element tree?

To create an element tree we only need to specify one or more child elements as the children prop of their containing element.

Why use this representation for a DOM node?

The reasoning behind using elements are: – easy to traverse
– don’t need to be parsed
– they are much lighter than the actual DOM elements—they’re just plain objects

What are component elements?

The type of an element can also be a function or a class corresponding to a React component, it does not have to be a string representing a DOM node. For example:


{
	type: Button,
	props: {
		color: 'blue',
		children: 'Test'
	}
}

This is the main idea of React: an element describing a component is also an element, just like an element describing the DOM node. They can be nested and mixed with each other.

Can I mix DOM and component elements?

Yes, that is the main idea of React. For example:


const SignoutAccount = () => ({
	type: 'div',
	props: {
		children: [{
			type: 'p',
			props: {
				children: 'Are you sure?'
			}
		}, {
			type: ConfirmButton,
			props: {
				children: 'Yes'
			}
		}, {
			type: Button,
			props: {
				color: 'blue',
				children: 'No'
			}
		}]
	}
}
});

Or in the JSX representation:


const SignoutAccount = () => (
{
  	<div>
  		<p>Are you sure?</p>
  		<ConfirmButton>Yes</ConfirmButton>
  		<Button>No</Button>
  	</div>  	
});

Are React elements immutable?

Yes, React elements are immutable. Once an element gets created, its children or attributes cannot be changed. An element represents the UI at a certain snapshot point in time.

Does React update the entire DOM?

No, React updates only the DOM parts that have changed.

For more information please visit the documentation on the reactjs.org.

React Basics React Components

2 minutes read

Rendering React components is very important since it can make your app behave faster or slower, depending on your approach for rendering components, re-rendering components based on condition or state/props change.

Here are a few methods you can use to render React components:

If Else conditional operator


import React from 'react';
import ReactDOM from 'react-dom';

function GuestComponent() {
    return <h1>Welcome guest</h1>
}

function BlogComponent() {
    return <h1>Welcome back</h1>
}


function MyComponent(props) {
    const isSubscribed = props.isSubscribed;

    if(isSubscribed) {
        return <BlogComponent />;
    }

    return <GuestComponent />
}

export default MyComponent;

ReactDOM.render(
    <MyComponent isSubscribed={false}/>,
document.getElementById('root'))

Ternary operation in React

Conditionally rendering React elements inline means to use the JavaScript conditional operator:

condition ? expr1 : expr2


import React from 'react';
import ReactDOM from 'react-dom';

function GuestComponent() {
    return <h1>Welcome guest</h1>
}

function BlogComponent() {
    return <h1>Welcome back</h1>
}


function MyComponent(props) {
    const isSubscribed = props.isSubscribed;
    return (
        <>
            { isSubscribed?
                <BlogComponent /> :
                <GuestComponent />
            }
        </>
    )
}

export default MyComponent;

ReactDOM.render(
    <MyComponent isSubscribed={false}/>,
document.getElementById('root'))

Inline If with Logical && Operator

In JS
true && expression
always evaluates to expression, so it will render, accordingly
false && expression
always evaluates to false, so React will ignore and skip it.

import React from 'react';
import ReactDOM from 'react-dom';


function MyComponent() {
    const errors = ['error1', 'error2'];

    return (
        <>
            { errors.length > 0 &&
                <h2>
                    You have {errors.length} errors.
                </h2>
            }
        </>
    )
}

export default MyComponent;

ReactDOM.render(
    <MyComponent />,
document.getElementById('root'))

Inline If-Else with Conditional Operator


import React from 'react';
import ReactDOM from 'react-dom';


function MyComponent() {
    const isLoggedIn = false;

    return (
        <div>
            The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
        </div>
    );
}

export default MyComponent;

ReactDOM.render(
    <MyComponent />,
document.getElementById('root'))

Return null to Prevent Component from Rendering

Returning null from a component’s render method does not affect the firing of the component’s lifecycle methods.


import React from 'react';
import ReactDOM from 'react-dom';


/**
 * @return {null}
 */
function MyComponent(props) {
    if (!props.warning) {
        return null;
    }

    return (
        <div className="warning">
            Warning!
        </div>
    );
}

export default MyComponent;

ReactDOM.render(
    <MyComponent warning={true} />,
document.getElementById('root'))

Immediately-invoked function expressions

Functions that are executed immediately after they are defined:



( function (/* arguments */) {
    // ...
} ) (/* arguments */);

Or with arrow functions:


( (/* arguments */) =&gt; {
    // ...
} ) (/* arguments */);

React Basics React Components

1 minute read

Components are JavaScript functions or classes that let you split the UI in reusable pieces.

Components accept arbitrary input named props and return React elements which describe what should appear on the screen.

React component types

Function components

The simplest way to define a component is by writing a function that accepts a single props object as an input parameter and returns the React element that should appear on the screen.

Example implementation of a function component:


import React from 'react';

function LoginBar(props) {
	return <h1> Logged in as {props.username} </h1>
}

export default LoginBar;

Class components

The same component can be written as an ES6 JavaScript class.

Example implementation of a class component:


import React, { Component } from 'react';

class LoginBar extends Component{

	render(){
		return(
			<h1> Logged in as {this.props.username} </h1>
		);
	}
}

export default LoginBar;

The two components are identical from React’s point of view.

Always use component names starting with capital letters. React treats components starting with lowercase letters as DOM tags. As an example the


<div /> 
represents a DOM tag but the

<LoginBar />
represents a component and requires LoginBar to be in scope.

More details related to rendering React components.

Fundamentals

2 minutes read

There are a few options to achieve that if you are using npm prior to version 5.2.0 and we list all options below.

If you are using npm greater than 5.2.0, have a look at our previous article how to use npx the npm package runner.

  1. First option would be to export the path in the .bashrc (or .zshrc file, depending on which one you use).

If you put the following


./node_modules/.bin

into your PATH variable it only works when your current working directory is the root of your project directory structure

Here is the npm command to get the path of locally install binaries:


npm bin

which will output a similar path


/Users/[user]/[project]/node_modules/.bin

Prior to npm 5.2.0, you should add the following to you PATH variable to execute a locally install module:


PATH=$(npm bin):$PATH jest

You can also create an alian for the execute command similar to:


alias npm-run='PATH=$(npm bin):$PATH'

and then you can run the following:


npm-run jest

or go even further


alias jest="npm-run jest"

Node: don’t forget to source your .bashrc (or .zshrc file in your terminal with


source .bashrc

or


source .zshrc

  1. Second option is to export the path to .bashrc (or .zshrc file, depending on which one you use).


export PATH="$(npm bin):$PATH"

  1. Third option is to to use npm scripts in package.json, because the always lookup the local binaries first.
    You can set up aliases or just use generic naming convention for scripts like “build”, “test”, “run:local”, “run:prod”, etc.

More details related to npm scripts.


"scripts": {
    "mymodule": "mymodule"
}

Then you can run with:


npm run mymodule

and even use arguments:


npm run mymodule -- args

Fundamentals

2 minutes read

NPX is a NPM package runner, which means it makes it easy to use command line (CLI) and other executable tools from the npm registry.

What’s the difference between npm and npx?

  • npm installs the packages from the registry.
  • npx helps with executing the node package.

How to install npx?

npx is included in npm > 5.2.0 as an extra binary, if you have npm installed you already have npx on your system.

To check if npx is installed, you can run this command:


which npx

If for some reason, you get npx command not working or npx command not found error message, you can manually install npm globally with the following command:


npm i -g npx

How to run npx?

The way to run npx is as follows:


npx < command >

Do I need to install < command > module in my $PATH before running npx < command >?

No, npx is smart enough in that if it does not find in your $PATH it will install an npm package from the registry with the same name as < command > and invoke it. Once the command has run the new package will be removed from your globals so you don’t have to worry about pollution on the long term.

What are some examples of using npx?

  1. Check for outdated, incorrect, and unused dependencies: npx npm-check
  2. Generate a react app boilerplate: npx create-react-app my_app
  3. Get a happy birthday message in different languages: npx happy-birthday -u John
  4. Make people believe you are working hard: npx workin-hard

How to execute local packages without using npx?


npm install package-to-execute
$ ./node_modules/.bin/package-to-execute

Can I execute packages by only using their name without using npx?

Yes, but only if the packages are installed globally.
For example:
$ npm install -g happy-birthday
$ happy-birthday -u John

🎂
Grattis på födelsedagen, John!
🎉
$ npm uninstall -g happy-birthday

Locally installed packages will only work to be executed by name if
you edit the package.json file and add the package to the scripts like the following:

 {
"name": "test_app",
"version": "1.0.0",
"scripts": {
"package-to-execute": "package-to-execute"
}
}

After that use the npm run package-to-execute.

Can I use npx with a version of npm < 5.2.0?

Yes, but you have to install npx globally.


npm install -g npx

Fundamentals

3 minutes read

For a basic JSX introduction you can check our previous article, Introduction to JSX.

JSX is actually syntactic sugar for defining components using the React.createElement(component, props, …children) function and positioning them inside the markup.

This is how you write a simple component in JSX and how Babel compiles it:

JSX code:

<div className="container">
    Hello World!
</div>
Compiler using Babel to:

React.createElement(
  'div',
  {className: 'sidebar'},
  null
)

This is how you define a Class Component in React using JSX:


import React, {Component} from 'react';

class MyComponent extends Component {
    render() {
        return (
            <div className="container">
                Hello World!
            </div>
        )
    }
}

export default MyComponent;

This is how you define a Functional Component in React using JSX:


import React from 'react';

function MyComponent () {
    return (
        <div className="container">
            Hello World!
        </div>
    )
}

export default MyComponent;

It’s preferable to use Functional Components since it’s much easier to read/write and understand.

As you see from the code, the component created is called MyComponent, it’s a best practice that the filename to be identical MyComponent.js.

Scopes

When you are using JSX code, React must always be in scope, since it’s getting compiled into calls to the React.createElement function.

Also, if you component is using another component, the that React component must as well be in scope, for example:


import React from 'react';
import MyOtherComponent from './MyOtherComponent';

function MyComponent () {
    return (
        <div className="container">
            <MyOtherComponent />
        </div>
    )
}

export default MyComponent;

Dot Notation for React Components with JSX

You can define your components in an object, and render then by calling the [object].[your-component], as you can see below.
However, would not recommend using it like this in a production ready application, since it’s more confusing.
Separating components per each file helps with the separation of concerns, each component that you build should be responsible of one thing and one thing only.


import React from 'react';

const MyComponents = {
    DatePicker: function DatePicker(props) {
        return <div>Imagine a {props.color} datepicker here.</div>;
    },
    MyComponent: function MyComponent() {
        return <div>Hello World!</div>
    }
}

function MyListOfComponents() {
    return (
        <div>
            <MyComponents.DatePicker color="blue" />
            <MyComponents.MyComponent />
        </div>
    );
}

export default MyListOfComponents;

Component Types

Built-In Components

When you are using any HTML tag like , or as the start of your component, it must start with a lower case. The string is the passed to the React.createElement as ‘div’, ‘span’ or ‘p’.

User-Defined Components

They should always start with a capital letter, so that you know it refers to a component you’ve build yourself and is not a built-in one.

Embedding Expressions in JSX

You can easily define variables in JS and use the inside your JSX component, just surround the name of the variable in curly braces and then you can take advantage of the JS power.


import React from 'react';

function MyComponent () {
    const name = 'John Doe';
    const age = 10;

    return (
        <div className="container">
            Hello World! My name is {name} and my age is {age*2}
        </div>
    )
}

export default MyComponent;

Empty tags can be closed immediately with />.
Same with self-closing HTML tags (img, br and others):


return (
        <div className="container">
            Hello World!
            <br />
            My name is {name} and my age is {age}
        </div>
    )

React Basics

2 minutes read

JSX is JavaScript with XML, still just JavaScript but with some extra functionality. The code written with JSX is looks very similar to HTML or XML, but the power comes from easily mixing JavaScript methods and properties with your HTML look-alike code.

Note

React can work fine without JSX, however writing React components with JSX, makes it easier and cleaner, it’s an ideal technology to use with your React application.

For example, Vue.js – The Progressive JavaScript Framework, actually supports JSX out of the box.

Introduction to JSX

JSX syntax can be converted using Babel, and rendered to JavaScript code so that your React application can understand, more details here.

Basically, you are not describing the UI using Strings, instead you take advantage of the JavaScript power, which allows you to do a lot of nice things, and without so much boilerplate code.

Browsers cannot execute JavaScript files containing JSX code, files need to be transformed to regular JS, though a process called transpiling.

JSX advantages

  • faster then normal JavaScript code, code optimizations happen while translating the code from JSX to normal JavaScript
  • easier to create UI templates
  • easier to understand how the UI will look and behave, since the markup and logic are in the same file, in components.

How to use JSX?

Let’s a have a look how we can show Hello World! using JSX.


const element = <h1>Hello World!</h1>;

Attributes using JSX

In order to switch from JSX code to JavaScript, you need to wrap the code into curly braces, so you can easily update an attribute written in JSX with the value of a predefined variable, something like this:

 const idAttribute = 'firstheading' const element = <h1 id="{idAttribute}">Hello World!</h1> 

Attributes written with JSX are written with camelCase convention. Also, good to know that the class and for attributes need to be written as className and htmlFor.

By using Babel, you can write this kind of code, and rely on the transpiling to do the heavy work, for example:

JSX code


const profile = <div>
  <img src="avatar.png" className="profile" />
  <h3>{[user.firstName, user.lastName].join(' ')}</h3>
</div>;

JS code transpiled using Babel


var profile = React.createElement("div", null,
  React.createElement("img", { src: "avatar.png", className: "profile" }),
  React.createElement("h3", null, [user.firstName, user.lastName].join(" "))
);

React Elements are JavaScript Objects, with details needed to describe a single node in the DOM.

Properties of a React Element that are worth caring about:

  • type specifies what type of HTML element to use;
  • props specify the attributes on the element
  • children lets you specify the element’s content

React.createElement() function requires a type and props as the first two arguments, with all other arguments treated as the element’s children.