Kselax.ru

Hacker Kselax – the best hacker in the world

Menu
  • Blog
  • Contacts
  • wp plugin generator
  • English
    • Русский
Menu

React the basic course. From newbie to ninja

Posted on 27 October, 201831 October, 2018 by admin

Hi. In this article I’ll explain to you how to use react. How to learn it the basic. To the end of which you will able to create powerful react app and will know some pitfalls.

Let’s get started. I’m a new to React and decided to create this masterpiece like a crib where I’ll store all the information that I’ll be learn.

 

links:

  1. React official documentation on site link
  2. Create react app. Getting started guide link

content table:

 

Code:

my tic-tac-toe link
React calculator link

 

#How to highlight JSX in sublime

you can use this the OCEANIC NEXT COLOR SCHEME link
and babel-sublime package link

 

#How to include React to the HTML file

you can do this by using CDN and you have to include react and react-dom

1
2
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

this is development, in production you have to change on production.min

Now you can create a first react app

1
2
3
4
5
6
7
8
9
10
const e = React.createReact;
const element = e(
  'h1',
  {className: "hello", id: "here_I_m"},
  'Hello world'
);
RenderDOM.render(
  element,
  document.getElementById('root')
);

you can’t use JSX in React unless you include babel be careful this code will not work.

1
2
3
4
5
const element = <h1>Hello world</h1>;
RenderDOM.render(
  element,
  document.getElementById('root')
);

Make it work include this babel by this line

1
2
<!-- Don't use this in production: -->
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

Don’t use babel in production because it will compile code and your app will work little slowly.

you have to use type=”text/babel” with <script> whatever you do

1
2
3
<script type="text/babel">
// here is JSX
</script>

or

1
<script type="text/babel" src="index.js">

without type=”text/babel” you’ll get an error

JSX

JSX is a javaScript syntax extension this is the thing, which is should be compiled by babel. Babel is a javaScript compiler link. You can’t use JSX without include babel to a html file.

 

#Rendering in React

in react exists elements and components. Don’t confuse elements with components. The elements are what components are “made of”. One component could have many elements.

We have an element <div id=”root”></div> in the DOM. React put inside the div#root and handles it by using a ReactDOM object.

1
2
3
4
ReactDOM.render(
  <h1>Hello world</h1>
  document.getElementById('root')
);

Everything inside dom#root will be managed by ReactDOM.

 

#Components

Always call components form capital letters. React will recognize it like components. If you call from lowercase letters it will be recognized as a tag. link

Could be two types of react components:

Functional component

1
2
3
function Welcome(props){
  return <h1>Hello {props.name}</h1>;
}

class component

1
2
3
4
5
class Welcome extends React.Component{
  render(){
    return <h1>Hello, {this.props.name}</h1>;
  }
}

You can pass data to the component by specify attributes

1
<Welcome name="Neo">

and get the data like props.
The main rule of thumb you can’t change prop in React components. It should be like pure functions

 

#State and lifesycle

Three things that you should know about setState()

1. Do not modify state directly link

//wrong
this.state.comment=”Hello”

//right
this.setState({comment: “Hello”})

2. State updates could be asynchronous link

1
2
3
4
// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

use function

1
2
3
4
// Correct
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

3. State updates are merged

react will merge the current state you provide with each call of the this.setState(); link

 

lifesycle it’s when component allocate resources and releafe when it destroy. In react are two event mount it’s when the component mounted to the DOM and unmount it’s when the component unmounted from the DOM.
In the class component we use two methods
componentDidMount(){}
and
componentWillUnmount(){}

 

Event handling

In react we can handle events

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Butt extends React.Component{
  constructor(props){
    super(props);
    this.state = {isOn: true}
    this.hClick = this.hClick.bind(this);
  }
 
  hClick(){
    this.setState(state => ({isOn: !state.isOn}))
  }
 
  render(){
    return(
      <button onClick={this.hClick}>
        {this.state.isOn ? 'On' : 'Off'}
      </button>
    );
  }
}
 
ReactDOM.render(
  <Butt />,
  document.getElementById('root')
);

to avoid bind exists two alternative syntaxies

The first. We can use class fields

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Butt extends React.Component{
  constructor(props){
    super(props);
    this.state = {isOn: true}
  }
 
  hClick = () => {
    console.log(this);
    this.setState(state => ({isOn: !state.isOn}))
  }
 
  render(){
    return(
      <button onClick={this.hClick}>
        {this.state.isOn ? 'On' : 'Off'}
      </button>
    );
  }
}

the second we can use with an event

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Butt extends React.Component{
  constructor(props){
    super(props);
    this.state = {isOn: true}
  }
 
  hClick() {
    console.log(this);
    this.setState(state => ({isOn: !state.isOn}))
  }
 
  render(){
    return(
      <button onClick={(e) => this.hClick(e)}>
        {this.state.isOn ? 'On' : 'Off'}
      </button>
    );
  }
}
 
ReactDOM.render(
  <Butt />,
  document.getElementById('root')
);

More preferable it’s to use the first variant with a bind in constructor. 

 

#Conditional rendering

 

#lists and keys

we have to specify keys only when we do map() link

 

#Forms

textarea creates like input tag
<textarea value={this.state.value} onChange={this.handleChange} />

 

#Lifting state up

an example link

Here is my example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
function c_to_f(value){
  let x = value * 9 / 5 + 32;
  return Math.round(x);
}
 
function f_to_c(value){
  let x = (value -32) * 5 / 9;
  return Math.round(x);
}
 
function Verdict(props){
  if(props.temperature >= 100){
    return <p>The water will boil</p>;
  }
 
  return <p>The water will not boil</p>;
}
 
class Calculator extends React.Component{
  constructor(props){
    super(props);
    this.state = {t_c: '', t_f: ''};
    this.hChangeCelcius = this.hChangeCelcius.bind(this);
    this.hChangeFahrenhait = this.hChangeFahrenhait.bind(this);
  }
 
  hChangeCelcius(t){
    this.setState({t_c: t, t_f: c_to_f(t)});
  }
 
  hChangeFahrenhait(t){
    this.setState({t_f: t, t_c: f_to_c(t)});
  }
 
  render(){
    return (
      <div>
        <TempritureField temperature={this.state.t_c} hChange={this.hChangeCelcius} t="c" />
 
        <TempritureField temperature={this.state.t_f} hChange={this.hChangeFahrenhait} t="f" />
 
        <Verdict temperature={this.state.t_c} />
      </div>
    );
  }
}
 
class TempritureField extends React.Component{
  constructor(props){
    super(props);
    this.state = {label: ''};
    if(props.t == 'c'){
      this.state.label = "Input temperature in Celsius:";
    } else if(this.props.t == 'f'){
      this.state.label = "Input temperature in Fahrenhait:";
    }
 
    this.hChange = this.hChange.bind(this);
  }
 
  hChange(e){
    this.props.hChange(e.target.value);
  }
 
  render(){
    return (
      <fieldset>
        <label>
          {this.state.label}
          <br />
          <input type="text" onChange={this.hChange} value={this.props.temperature} />
        </label>
        
      </fieldset>
    );
  }
}
 
ReactDOM.render(
  <Calculator />,
  document.getElementById('root')
);

 

 

 

#Some new expressions

state=>({foo: “bar”}) this is an arrow function that means function(state){ return {foo: “bar”}}. Here we used a () because we can’t return an object like an expression.

How to fill an array:

1
Array(9).fill(null);

 

Destructuring assignment link

1
cosnt [a,b,c] = line[i];

or

1
2
3
const ar = [1,2,3,4];
const [a,b,c,d] = ar;
console.log('sum = ' + (a+b+c+d) );

 

concat link

1
2
3
4
5
6
7
8
9
this.setState({
  isX: !this.state.isX,
  history: history.concat([
    {
      squares: squares
    }
  ]),
  stepNumber: stepNumber,
})

 

a new syntax link

1
2
3
const obj={a: 1, b: 2, c: 3}
const {a, b, c} = obj;
console.log(a + b + c); //6

 

the es6 spread operator link

1
2
3
4
const ar1 = [1,2,3];
const ar2 = [...ar1, 5];
console.log('ar2 = ', ar2);
console.log('ar1 = ', ar1);

 

closure by ()()

1
2
3
4
5
6
7
8
9
10
app.get('/login', function(req, res, next){
  passport.authenticate('local', function(err, user, info){
    if(err) { return next(err); }
    if(!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if(err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

 

 

 

the end

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • bash (1)
  • English (9)
  • JavaScript (4)
  • node.js (22)
  • photoshop (1)
  • php (3)
  • React (9)
  • sclerotic (6)
  • Ubuntu (10)
  • Uncategorized (15)
  • Wordpress (1)

Tags

Ajax apache2 automation bash chrome-extension command line editor ejs email English English-grammar framework functions git graphql handlebars hybrid app installation javascript js linux newbie node.js node.js javascript nodemailer npm objects Performance php phpmyadmin playonlinux promise rabbitmq React react-router redis reverse-proxy session shell socket.io sublime text 3 time zones ubuntu unity webpack

Recent Comments

  • damien on How to install npm and nodejs the latest versions on ubuntu
  • Cam on How to install npm and nodejs the latest versions on ubuntu
  • Pierre on socket.io with apache as a reverse proxy on the CentOS
  • admin on How to use react-router with a few languages
  • admin on How to install npm and nodejs the latest versions on ubuntu
©2021 Kselax.ru Theme by ThemeGiant