React Js learning dairy part 12

Props and State difference

In React props and state is used quiet a lot to store dynamic information

But what the difference?

props: is immutable and it is can only be changed by a different component

state: be changed by the component itself

still confusing…. for me either,

That’s dig out first props:

for example:

class Hi extends React.Component {
    render(){
      return <h1>Hello, {this.props.name}</h1>;
    }
}

cont element = <Hi name='tess' />;

name attribute property could be also called as defaultPrpos:

Hi.defaultProps = {
    name: 'tess',
};

so props like an argument is passed to a function, to be simpler:

function Hi(props){
    return <h1> Hello, {prps.name} </h1>;
}

PlayCode here

Then dig out  states:

The key difference from props is: state working in action by component itself, the action are: create, update and use state

for example:

A button keep track of how many times had clicked

First set state it’s initial data:

constructor() {
  super();
  this.state = {
    count: 0,
  };
}

This has set in constructor, in this example we set count init value 0

Then Let’s set method to change state :

updateCount() {
  this.setState((prevState, props) => {
    return { count: prevState.count + 1 }
  });
}

here we set setState function, and it need callback function to update state directly

Here access prevState  : previous state in order to count the click

Please notice prevState is from setState Api
Always remember this argument if need to track of the output of updater

cause use follow code will through error in React

this.setState({
   value: this.state.value + 1 // prone to bugs
 });

Final, render the result

render() {
  return (<button
            onClick={() => this.updateCount()}
          >
            Clicked {this.state.count} times
          </button>);
}

tthis.updateCount() will be called,

() => , this is called Arrow function in ES6

so this will rendre result of click times

playCode here

Next since it is clear about props and state,

Get further next tutorial we will get through the stateful parent component to stateLess child component

lazy load js

what is lazy load, the basic concept is spped up page loading time especially it’s comes to lots images

There’s some library to use for, like echo.js
or beLazy.js

Here we introduced lazy-load-xt

Why?

Simply it does support: css animation like transitions affect, it is support scrollable containers like IFRAME contend, and more other media like videos, and even no script support ( disable js support)

well, it is just more powerful, but if you simply just want load images faster you could consider just use upper introduced library

But remember it is has to user jQuery 1.7

How to use?

1 Installation:

You could install by node js or bower

$ npm install lazyloadxt
$ bower install lazyloadxt

or simply use this cdn

2 add html tag to called the image src, or you could defined a variable to call image src

data-src

3 Then defined image size or any css style for layout

4 That’s it you should be able see the image load

and here has so API to play with

$.extend($.lazyLoadXT, {
  edgeY:  200,
  srcAttr: 'data-src'
});

output:

 

code play here

React Js learning dairy part 11

Pass state from Child component(Export) to Parent component(Import)

Last lesson we knew how to pass state from a method

But what if we need to pass by another component?

Here is the process:

1 Child component(Export):

A inside rendre(), returnthis.props.yourAttributeName , in this cas we called our attribute : name

return <h1>Hey, my name is {this.props.name}!</h1>;

2 Parent component(Import):

A inside constructor(), stored attribute value in this.state

B render(), return this attribute value

Output:

 

React Js learning dairy part 10

Call this.setState from Another Function

As we learned State how to access data to component, and it is important to know how to access from another method or Function

This could be useful like attribute a value with event handler

Process:

1 Defined a function method or event handler

 changeColor() {
    const newColor = this.state.color == green ? yellow : green;
    this.setState({ color: newColor });
  }

2 Assign this method with bind(this) in constructor

constructor(props){
    super(props);
    this.state = { color: green };
    this.changeColor = this.changeColor.bind(this);
  }

3 rendre this click event

<button onClick={this.changeColor}>

Output:

online coder

React Js learning dairy part 9

state: A component decides its own state,  and access dynamic information

( Not like Props, which could passed in from outside the component)

use: give the component a state property. This property should be declared inside of a constructor method

sample:

constructor(props) {
  super(props);
  this.state = { title: 'Best App' };
}

call state:

{this.state.title }

output:

online coder

React Js learning dairy part 8

this.props.children : will return everything in between a component’s opening and closing JSX tags

Basic like an interface we need to put different content:

<Grid>
  <Row />
  <Row />
  <Row />
</Grid>

Row are as child to pass the Grid component as props.children

So as Grid is the parent it has to declare props children :

class Grid extends React.Component {
  render() {
    return <div>{this.props.children}</div>
  }
}

the parent can also decide not to render any children, as follow the basic sample to rendre either with/ without child :

And Everything can be a child

could be a text, could be a function, or Js expression

class Executioner extends React.Component {
  render() {
    // See how we're calling the child as a function?
    //                        ↓
    return this.props.children()
  }
}

Or fectch some data from a server:

<Fetch url="api.myself.com">
  {(result) => <p>{result}</p>}
</Fetch>

Sample: 

As you see you want to show your favorite Musician title + list albums

Process:

1 Parent component:

A. add : import { Export class } from ‘./Export class’;

B. Inject:

<Export class  props.attribute ='any value'/></Export class>

C. Inside Export class, add: html element

import React from 'react';
import ReactDOM from 'react-dom';
import { List } from './List';

class App extends React.Component {
  render() {
    return (
      <div>
        <List type='Living Musician'>
          <li>Sachiko M</li>
          <li>Harvey Sid Fisher</li>
        </List>
        <List type='Living Cat Musician'>
          <li>Nora the Piano Cat</li>
        </List>
      </div>
    );
  }
}

 

2 Child part:

A. Declare prop. attribute name, ex: let type= this.props.type ( or this.props. yourDefinedAtrributeName )

let titleText = `Favorite ${this.props.type}`;

B. set logical to show your defined attribute value

if (this.props.children instanceof Array) {
        titleText += 's';
    }

C. return this instance list value

 return (
      <div>
        <h1>{titleText}</h1>
        <ul>{this.props.children}</ul>
      </div>
    );

So far this is very sample demo which allow the props children passer data to parent component, props child could be very complex such iterating api by use map, foreach, but it should be later on lesson ( I’m still in learning process……)

Next we will get through state

Installed ngrok in Mac

Hey back again!! Take a little break from React js tutorials

Today show the most simple demostration your work in local host via Ngrok

why we talk about Ngrok, because as play around with React js you need your

server has node js environment, well, if you are using MAC then node js is quiet simple installed through Homebrew

Then pretty much work around with npm install to creat your first react js app

The problem is if you want to show your practice project from your local work?

Then it is come to complicated, that’s why we talk about Ngrok

what is Ngrok ? well it is secure tunnel to pass your localhost, and transfer it readable url, with this url you could show your local work without any deploy work such as to cloud or dedie server, never mention those tedious configuration work

Sounds good? let start the process:

1 installed Homebrew

2 installed ngrok from terminal, using this command:

$ brew cask install ngrok

3 $ ngrok http 3000 ( which is react js local host default port)

that’s all,

Then you will see the terminal running like this:

As you could see the http:// xxxx.ngrok.io   is the URL generated by ngrok which allowed show your local work directly

 

React Js learning dairy part 7

Put an Event Handler in a Component Class

Here we want put a button, which as click once it will add blah text once, click twice it will add blah text twice……

Here is the process:

1 . Import part:

A. add : import { Export class } from ‘./Export class’;

 

import { Button } from './Button';

B.  Inside class we define an event handler method:

talk () {
    let speech = '';
    for (let i = 0; i < 10000; i++) {
      speech += 'blah ';
    }
    alert(speech);
  }

2 Export part: inside Export class, inside return function, in the click Html element, add

onClick={this.talk}

That’s it, pretty simple, in Parent class we add the child class in render() function inside return

render() {
    return <Button />
  }

Here is the whole code:

Parent class:

import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from './Button';

class Talker extends React.Component {
  talk () {
    let speech = '';
    for (let i = 0; i < 10000; i++) {
      speech += 'blah ';
    }
    alert(speech);
  }
  render() {
    return <Button />
  }
}

ReactDOM.render(
  <Talker />,
  document.getElementById('app')
);

Child Class:

import React from 'react';

export class Button extends React.Component {
  render() {
    return (
      <button onClick={this.talk}>
        Click me!
      </button>
    );
  }
}

Next tutorials we will learn this.props.children

React Js learning dairy part 6

This is suite of Props

Put props and pass to another component

the logical is the same as a component renders another component

Here is the processing:

1.Export Class: add export in which class you want to rendre l’info

import React from 'react';

export class Greeting extends React.Component {
  render() {
    return <h1>Hi there, {this.props.name}!</h1>;
  }
}

2.Import Class:

A.add : import { Export class } from ‘./Export class’;

import { Greeting } from './Greeting';

B. add : in rendre() :

<Export class  props.attribute ='any value'/>
<Greeting  name='tess'/>

As you could found, Greeting is the Export Class we defined in 1,  and we had passer props attribute in this case is name , then assign value to this attribute

Next we will show how to put event  handler in a component Class

React Js learning dairy part 5

This is short tutorial for Props

Props: Passing a prop by giving an attribute to a component instance

Accessing a passed-in prop via this.props.prop-name

Using a prop to make decisions about what to display

A component’s props is an object. It holds information about that component.

To see a component’s props object, you use the expression this.props. Here’s an example of this.props being used inside of a render method:

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

class PropsDisplayer extends React.Component {
  render() {
    const stringProps = JSON.stringify(this.props);

    return (
      <div>
        <h1>CHECK OUT MY PROPS OBJECT</h1>
        <h2>{stringProps}</h2>
      </div>
    );
  }
}

// ReactDOM.render goes here:
ReactDOM.render(
  <PropsDisplayer />,
  document.getElementById('app')
)