React Js learning dairy part 21

componentWillUpdate

  1. gets called in between shouldComponentUpdate and render
  2. receives two arguments: nextProps and nextState.
  3. to interact with things outside of the React architecture, EX: window size or interacting with an API, animation

example:

componentWillUpdate: function(nextProps, nextState) {
        nextState.events.push("Updating component");
    }

Another example:

componentWillUpdate(nextProps,nextState) { 
if (document.body.style.background != yellow && this.state.highest >= 950*1000) { 
   document.body.style.background = yellow; 
 }
 else if (!this.props.game && nextProps.game) { 
   document.body.style.background = 'white'; 
 } 
} 

here as first inject basic 2 arguments: nextProps and nextState, here you are not allowed to call this.setSate(), only if you need to update state in response to props change, use componentWillReceiveProps() instead

and componentWillUpdate() will not be invoked if shouldComponentUpdate() returns false

 

React Js learning dairy part 20

Updating Lifecycle Methods

For updating, here has some method to use:

  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate

Here we will introduced those 2 methods first

  • componentWillReceiveProps
  • shouldComponentUpdate

componentWillReceiveProps

  1. CALLED: only if component will receive props
  2. CAPTURE THE LAST VALUE
  3. receives nextProps as an argument

example:

componentWillReceiveProps(nextProps){
    this.setState({user: nextProps.user})
  }

if you write follow code instead:

componentWillReceiveProps(){
    this.setState({user: this.props.user})
  }

Then you will not have new state and just setting user back to its current state

PlayCode here

shouldComponentUpdate

  1. compare lifecycle method
  2. automatically receives two arguments: nextProps and nextState
  3. compare nextProps and nextState to the current this.props and this.state, return boolean

example:

 shouldComponentUpdate(nextProps, nextState) {
    if ((this.props.text == nextProps.text) && 
      (this.state.subtext == nextState.subtext)) {
      alert("Props and state haven't changed, so I'm not gonna update!");
      return false;
    } else {
      alert("Okay fine I will update.")
      return true;
    }
  }

As you could shouldComponentUpdate nextProps and nextState arguments, and compare those 2 value, if the props ans state haven’t changed it return false

Here has the same funtionality called PureRenderMixin
As by experts it is advice to avoid use shouldComponentUpdate as for debugging side since it will not render as return false,

Here has good article for it, if you like to check and deep more

PHP learning diary: MVC for crud

Today get back to php

Here we used to use MVC mode to cread, read, update and delete data to our view

The intermedia is controller which should be integrate data from model, so this could bind to view for UI showing part, bref…….

Case studying:

You have a page which allowed user write their note and title of note

outPut:

As you could see here has title and content input for note page

Assume you should knew that Note page allowed by login user

what we want to do here is as user type the title and content value,

and hit submit, those value will save into our database, the case here I use is MySQL

let’s start:

Model:

create class called Model, where you basic get your DB host, name, user, pass

// db connect info
class Model {

	function __construct() {
		$this->db = new Database(DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS);
	}

}

Next we create class called Note_Model

class Note_Model extends Model{
 public function __construct()
	{
		parent::__construct();
	}
 public function noteList()
	{
		return $this->db->select('SELECT * FROM note WHERE userid = :userid', 
				array('userid' => $_SESSION['userid']));
	}
}

Here create public function noteList which read userid, noteid from $this->db->select()

select function had created in Database class

class Database extends PDO {
       /**
	 * select
	 * @param string $sql An SQL string
	 * @param array $array Paramters to bind
	 * @param constant $fetchMode A PDO Fetch mode
	 * @return mixed
	 */
	public function select($sql, $array = array(), $fetchMode = PDO::FETCH_ASSOC)
	{
		$sth = $this->prepare($sql);
		foreach ($array as $key => $value) {
			$sth->bindValue("$key", $value);
		}
		
		$sth->execute();
		return $sth->fetchAll($fetchMode);
	}
}

the same logical which we create date:

public function create($data)
	{
		$this->db->insert('note', array(
			'title' => $data['title'],
			'userid' => $_SESSION['userid'],
			'content' => $data['content'],
			'date_added' => date('Y-m-d H:i:s') // use GMT aka UTC 0:00
		));
	}

Here you could see $this->db->insert() which come from database class insert public function:

/**
	 * insert
	 * @param string $table A name of table to insert into
	 * @param string $data An associative array
	 */
	public function insert($table, $data)
	{
		ksort($data);
		
		$fieldNames = implode('`, `', array_keys($data));
		$fieldValues = ':' . implode(', :', array_keys($data));
		
		$sth = $this->prepare("INSERT INTO $table (`$fieldNames`) VALUES ($fieldValues)");
		
		foreach ($data as $key => $value) {
			$sth->bindValue(":$key", $value);
		}
		
		$sth->execute();
	}

here use bindValue to get column name and response value, in this case is title, content, date

As same logic for update, delete:

Update:

/**
	 * update
	 * @param string $table A name of table to insert into
	 * @param string $data An associative array
	 * @param string $where the WHERE query part
	 */
	public function update($table, $data, $where)
	{
		ksort($data);
		
		$fieldDetails = NULL;
		foreach($data as $key=> $value) {
			$fieldDetails .= "`$key`=:$key,";
		}
		$fieldDetails = rtrim($fieldDetails, ',');
		
		$sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where");
		
		foreach ($data as $key => $value) {
			$sth->bindValue(":$key", $value);
		}
		
		$sth->execute();
	}

Delete:

/**
	 * delete
	 * 
	 * @param string $table
	 * @param string $where
	 * @param integer $limit
	 * @return integer Affected Rows
	 */
	public function delete($table, $where, $limit = 1)
	{
		return $this->exec("DELETE FROM $table WHERE $where LIMIT $limit");
	}

note_model class:

Edit and save the data:

public function editSave($data)
	{
		$postData = array(
			'title' => $data['title'],
			'content' => $data['content'],
		);
		
		$this->db->update('note', $postData, 
				"`noteid` = '{$data['noteid']}' AND userid = '{$_SESSION['userid']}'");
	}

delete the date:

public function delete($id)
	{
		$this->db->delete('note', "`noteid` = {$data['noteid']} AND userid = '{$_SESSION['userid']}'");
	}

Controller:

Since we had model to trigger the data, now it is use controller bind those value between view and model:

In Controller folder, create class called Note which had parent class Controller ( in this class we assume had defined where to find the path of model and view ):

class Controller {

	function __construct() {
		//echo 'Main controller
';
		$this->view = new View();
	}
	
	public function loadModel($name) {
		
		$path = 'models/'.$name.'_model.php';
		
		if (file_exists($path)) {
			require 'models/'.$name.'_model.php';
			
			$modelName = $name . '_Model';
			$this->model = new $modelName();
		}		
	}

}

Note Class in Controller:

class Note extends Controller {

	public function __construct() {
		parent::__construct();
		Auth::handleLogin();
	}
	
	public function index() 
	{	
		$this->view->noteList = $this->model->noteList();
		$this->view->render('note/index');
	}
	
	public function create() 
	{
		$data = array(
			'title' => $_POST['title'],
			'content' => $_POST['content']
		);
		$this->model->create($data);
		header('location: ' . URL . 'note');
	}
	
	public function edit($id) 
	{
		$this->view->note = $this->model->noteSingleList($id);
	
		if (empty($this->view->note)) {
			die('This is an invalid note!');
		}
		
		$this->view->render('note/edit');
	}
	
	public function editSave($noteid)
	{
		$data = array(
			'noteid' => $noteid,
			'title' => $_POST['title'],
			'content' => $_POST['content']
		);
		
		// @TODO: Do your error checking!
		
		$this->model->editSave($data);
		header('location: ' . URL . 'note');
	}
	
	public function delete($id)
	{
		$this->model->delete($id);
		header('location: ' . URL . 'note');
	}
}

As you could see here has bind data through $this->model->(related public function)
and call http url by location parametre

That’s go to see the final View part:

in views/note folder, create index.php and edit.php file

Index show the principal page by form post method:



 

As below the form, you could add the table which allow edit, delete the note button:

use foreach to iterate over arrays of table note:

 

In edit.php, here you should allow user to edit their note

output:

As you could see sumit allowed user update/add what they had modified or add to dataBase:

React Js learning dairy part 19

In react it has lots methods for life cycle which allowed you from birth ( pre-mounting) and deatch (unmounting)

through life cycle we could let UI renders, updates, thinks about re-rendering and then disappears

Here we start just the birth part:

  • componentWillMount
  • render
  • componentDidMount

componentWillMount

define:

  1. this life cycle method is not used quiet often
  2. will be called only once, before the initial render
  3. will not be triggered when re-rendering

when to use?

  1. like window resizing or focus change
  2. fetch data
  3. render properly from other API

for example

componentWillMount() {
    let mode;
    if (this.props.age > 70) {
      mode = 'old';
    } else if (this.props.age < 18) {
      mode = 'young';
    } else {
      mode = 'middle';
    }
    this.setState({ mode });
  }

As you could see here has initial the value of mode by props attribute value

Another sample is set alert in componentWillMount , componentDidMount, render, you will see the alert order will be follow:

  1. AND NOW, FOR THE FIRST TIME EVER… FLASHY!!!!”  (componentWillMount)
  2. Flashy is rendering! (render)
  3. YOU JUST WITNESSED THE DEBUT OF… FLASHY!!!!!!!  (componentDidMount)
  4. ON SCREEN: OOH LA LA LOOK AT ME I AM THE FLASHIEST

PlayCode here

componentDidMount

define:

componentDidMount is called after the component is rendered for the first time. This can be used to start an async operation as soon as the component shows up

componentDidMount won’t be called in server rendering

usage:

best place to put calls to fetch data

for example:

componentDidMount() {
    this.UserList();
}

this is used to call AJAX api which define in UserList function

Since componentDIdMount called once after the component is rendered

PlayCode here

React Js learning dairy part 18

Talk about form we need to binding dynamic data which receive information from browser via those DOM elements:  <input><textarea>, and <select>

In React to do this there’s 2 method:

Controlled vs UnControlled

Controlled

in order to update the value, it’s need specify an onChange callback for the input. The event in the callback will have the new suggested value from the input. Then take that new value and put it somewhere in your state, then re-render with the new value

usage:

export class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = { userInput: '' };
    this.handleUserInput = this.handleUserInput.bind(this);
  }
  handleUserInput(e) {
      this.setState({
        userInput: e.target.value
      });
    }

  render() {
    return (
      <div>
        <input type="text" onChange={this.handleUserInput} value={this.state.userInput} />
        <h1>{this.state.userInput}</h1>
      </div>
    );
  }
}

as mentioned: to change input value with onChange attribute which contain the value by callback function: handleUserInput

each time as user put any value it will call handleUserInput, and render the value

A form element becomes controlled if you set if value via a prop, as followed form elements has a different prop for setting that value:

Element Value property Change callback New value in the callback
<input type="text" /> value="string" onChange event.target.value
<input type="checkbox" /> checked={boolean} onChange event.target.checked
<input type="radio" /> checked={boolean} onChange event.target.checked
<textarea /> value="string" onChange event.target.value
<select /> value="option value" onChange event.target.value

PlayCode here

UnControlled

  • it will have to get that information through props
  • has no memory, cause an uncontrolled component keeps the source of truth in the DOM
  • could be less code if you want to quick & dirty
  • use ref

usage:

class Form extends Component {
  handleSubmitClick = () => {
    const name = this._name.value;
    // do something with `name`
  }

  render() {
    return (
      <div>
        <input type="text" ref={input => this._name = input} />
        <button onClick={this.handleSubmitClick}>Sign up</button>
      </div>
    );
  }
}

Here pass a callback in the ref
PlayCode here

I knew it’s been trick, just remember if you had simple in terms of UI feedback, uncontrolled with refs if fine

also you could deep more this article here which I think it’s better explication

What to use? controlled or unControlled?

feature uncontrolled controlled
one-time value retrieval (e.g. on submit)
validating on submit
instant field validation
conditionally disabling submit button
enforcing input format
several inputs for one piece of data
dynamic inputs

React Js learning dairy part 17

PropTypes

Once app grow, it will difficult to check type as coming the bugs,

React provide library to check types

Usage:

1

import PropTypes from 'prop-types';

2

BestSeller.propTypes = {
  title:  React.PropTypes.string.isRequired,
  author: React.PropTypes.string.isRequired,
  weeksOnList: React.PropTypes.number.isRequired
};

Declare propTypes by your instance of class, as follow types you could use:

array, bool, func, number, object, string; symbol, element, node, instanceOf(yourClassName)

for more detail check doc here

3

<li>
        Title: <span>
          {this.props.title}
        </span><br />

        Author: <span>
          {this.props.author}
        </span><br />

        Weeks: <span>
          {this.props.weeksOnList}
        </span>

here in child class rendre props attribute

4

<BestSeller 
              title="Glory and War Stuff for Dads" 
              author="Sir Eldrich Van Hoorsgaard" 
              weeksOnList={10} />

In parent component called child class with attribute and assign them the value

Notice:

  1. PropTypes is an object ( not a function)
  2. your component class expects to receive, there can be one property on your propTypes object.
  3. Property: React.PropTypes.expected-data-type-goes-here (message: React.PropTypes.string)
  4. You can define default values for your props by assigning to the special defaultProps property:
Greeting.defaultProps = {
  name: 'Stranger'
};

outPut:

Next we will go through to React form

React Js learning dairy part 16

You might see this quiet often in react:

 componentDidMount()

this is called: Component life-cycle in react

this allowed us to update the UI and application state

there’s several life circle method in react, but here we just want to show the basic use like componentDidMount, there’s some crucial issue if user component WillMount method,

But I’m not familiar either so here simple show componentDidMount:

What to use:

This function will be called only once in the whole life-cycle of a given component and it being called the component — and all its sub-components — rendered properly.

usage:

cause side effects (AJAX calls etc.)

demo:

componentDidMount() {
    this.interval = setInterval(this.nextGP, 5000);
  }

this could be most use for setInterval

Before this life cycle you should call constructor to allowed initialise component itself, and binding the class method:

 constructor(props) {
    super(props);

    this.state = { currentGP: 0 };

    this.interval = null;

    this.nextGP = this.nextGP.bind(this);
  }

this bind initial state currentGP value as 0, and interval, also call the binding method to change next image

Remember never use setState in constructor

componentWillUnmount()

here use life cycle componentWillUnmount method to clearInterval

this life cycle use for setTimeout, setInterval, or performs any operations need to close/ remove when no need anymore

Remember never user this.setState in this life cycle method

so as fellow is the whole life cycle:

constructor() —–> componentDidMount() —–>componentWillUnMount()—–>render()—–>create all direct-child component

For more Component Lifecycle logical here has good practice link

outPut:

 

you could play code here

So here we had done some basic react, from next dairy we will go to advanced react part

React Js learning dairy part 15

Stateless Functional Components and Props

instead of written in class, you could write stateless function

They emphasize the fact that components are basically functions! A component takes two optional inputs, props and state, and outputs HTML and/or other components.

// Normal way to display a prop:
export class MyComponentClass extends React.Component {
  render() {
    return <h1>{this.props.title}</h1>;
  }
}

// Stateless functional component way to display a prop:
export const MyComponentClass = (props) => {
  return <h1>{props.title}</h1>;
}

// Normal way to display a prop using a variable:
export class MyComponentClass extends React.component {
  render() {
    let title = this.props.title;
    return <h1>{title}</h1>;
  }
}

// Stateless functional component way to display a prop using a variable:
export const MyComponentClass = (props) => {
    let title = props.title;
  return <h1>{title}</h1>;
}

You could pretty notice that with stateless function, you pass props as argument so when you set a variable you do not need retrieve by key word: this

 

React Js learning dairy part 14

Since we knew how to pass state from statefull parent Component to stateLess child Component

Here more further we want to pass an event handler

for example:

select input value dynamic update to child value

Parent stateful component:

Contructor

constructor(props) {
    super(props);

    this.state = { name: 'Tess' };
  }

here again set initial value name = Tess by state

Method to change name

changeName(newName) {
    this.setState({
      name: newName
    });
  }

use setState to update the value of name

Since had add this method, had to back constructor to bind this to get instance

constructor(props) {
    super(props);

    this.state = { name: 'Frarthur' };

    this.changeName = this.changeName.bind(this);
  }

final render the name value

render() {
    return <Child name={this.state.name} onChange={this.changeName} />
  }

import Child component and get attribute name value by state, binding event by onChange attribute, which set action by changeName method

Child stateless component:

Constructor

 constructor(props) {
    super(props);
  }

add method to handle change from broweser

 handleChange(e) {
    const name = e.target.value;
    this.props.onChange(name);
  }

set constant name to get browser value

and called onChange event, which change the constant name by this event argument

Since we had add method, back to constructor to bind

constructor(props) {
    super(props);

    this.handleChange = this.handleChange.bind(this);
  }

Final render the result

render() {
    return (
      <div>
        <h1>
          Hey my name is {this.props.name}!
        </h1>
        <select id="great-names" onChange={this.handleChange}>
          <option value="Frarthur">
            Frarthur
          </option>

          <option value="Gromulus">
            Gromulus
          </option>

          <option value="Thinkpiece">
            Thinkpiece
          </option>
        </select>
      </div>
    );
  }

output:

 

React Js learning dairy part 13

This suite de dairy part 12

We want to rewrite count click times component to separate with Parent and Child component

Let’s review back last chapter: Code here

So here first make ParentClass, which will has the state  and method to update the click times,

First in constructor

constructor(props) {
    super(props);

    this.state = { totalClicks: 0 };
  }

we set state totalClicks initial value= 0

Then as usual we add a method to count click times

handleClick() {
    const total = this.state.totalClicks;

    // calling handleClick will 
    // result in a state change:
    this.setState(
      { totalClicks: total + 1 }
    );
  }

This time we had set a constant variable total to get the state value

and use this.setState function to add 1 for each click state

Go back to constructor:

constructor(props) {
    super(props);

    this.state = { totalClicks: 0 };

    this.handleClick = this.handleClick.bind(this);
  }

compare last chapter, we had add this.handleClick = this.handleClick.bind(this);

we need to pass each instance by:

this.handleClick.bind(this)

this is because we had handleClick function to bind each time trigger, in react this is equal to ES6

() => this.handleClick()

And always render result:

// The stateful component class passes down
  // handleClick to a stateless component class:
  render() {
    return (
      <ChildClass onClick={this.handleClick} />
    );
  }

Did you remark in render() function we return another class in this case called: ChildClass ? instead of render result in Parent component here we want it is render in Child component

So let’s create Child component:

export class ChildClass extends React.Component {
  render() {
    return (
      // The stateless component class uses
      // the passed-down handleClick function,
      // accessed here as this.props.onClick,
      // as an event handler:
      <button onClick={this.props.onClick}>
        Click Me!
      </button>
    );
  }
}

Here we access onClick by props onclick method: onClick={this.props.onClick}

as mentioned before child component is stateless component, so only could pass data by props, so here we pass by this.props.onClick

which will called in Parent component by onClick attribute by assign the value by handleClick method

PlayCode here