JS.React. Wow! SetState is async )

The discussion is here.

In my code i did like this to get the proper result of the state

    setMyName(myName, f) {
        this.setState({myName}, () => {
            f()
        });
    }
...
handleImgClick = (e) => {
        this.setMyName('Stanley', () => {alert(this.state.myName)});
    }

Posted in Без рубрики | Leave a comment

Js.React. How do i search dom elements?

Example

    const handleRightClick = (e) => {
        const house = document.getElementById('1'); // << vanila js :))
        if (house) house.setAttribute('margin-left', '200px');
        house.style.marginLeft = '100px';
    }

FullCode

import {useState} from 'react';
import React from "react";
import styles from './NavigationBar.module.css';

export const NavigationBar = () => {

    const leftButtonValue = '<';
    const rightButtonValue = '>';

    const [myName, setMyName] = useState(0);

    const handleRightClick = (e) => {
        const house = document.getElementById('1');
        if (house) house.setAttribute('margin-left', '200px');
        house.style.marginLeft = '100px';
    }

    return (
        <div className={styles.navigation}>
            <progress className={styles.progress} value="0" max="100"></progress>

            <button className={styles.buttons__left} >
                {leftButtonValue}
            </button>
            <button className={styles.buttons__right} onClick={handleRightClick} >
                {rightButtonValue}
            </button>
        </div>
    );
}
Posted in Без рубрики | Leave a comment

JS. React. Components in class style and HOOKS

Source

import React {Component, useState} from 'react'; // destruct here
...
class House extends Component // for example

//  or example from docs
class Welcome extends Component {
  render() {
    return <h1>Привет, {this.props.name}</h1>;
  }
}
import React, {Component, useState} from "react";
import cc from 'classcat';
import styles from './House.module.css';

export class House extends Component {

    constructor(props) {
        super(props);
        this.state = {
            myName: 'noName',
        }
    }

    setMyName(myName) {
        this.setState({myName});
    }

   
    render() {

        const {
            src,
            alt,
            title,
            price,
            location,
            isSold
        } = this.props;

        const {myName} = this.state;

        const styleTitle = cc({
            [styles.title]: true,
            [styles.isSold]: isSold
        });

        const handleImgClick = (e) => {
            e.preventDefault();
            this.setMyName('Stanley');
            this.setState({myName: 'Stanley'});
            alert(this.state.myName);
        }

        return (
            <div className={styles.house}>
                <img className={styles.image} src={src} alt={alt} onClick={this.handleImgClick}/>
                <p className={styleTitle}>{title}</p>
                <p className={styles.price}>{price}</p>
                <p className={styles.location}>{location}</p>
            </div>
        );

    }

    handleImgClick(e) {
     this.setMyName('Stanley');
     alert(this.state.myName);
    }
}


Pure Component with ShallowEqual

HOOKS

Details of react h in docs

useEffect

usePrevious

shouldComponentUpdate -> useMemo

для event useCallback

Posted in Без рубрики | Leave a comment

JS.React. Components in functional style

install react

npx create-react-app my-app
cd my-app
npm start

Source code

What is interesting ?

Example of component

import React from "react";
import cc from 'classcat';
import styles from './House.module.css';

export const House = ({
                          src,
                          alt,
                          title,
                          price,
                          location,
                          isSold
                      }) => {

    const styleTitle = cc({
        [styles.title]: true,
        [styles.isSold]: isSold
    });

    return (
        <div className={styles.house}>
            <img className={styles.image} src={src} alt = {alt}/>
            <p className={styleTitle}>{title}</p>
            <p className={styles.price}>{price}</p>
            <p className={styles.location}>{location}</p>
        </div>
    )
}

Css module (work from the box in react), we can use style var or any other we define

...
import styles from './House.module.css'; // << add word module to css file for webpack
...

// below you can call like this
<div className={styles.house}>
            <img className={styles.image} src={src} alt = {alt}/>
            <p className={styleTitle}>{title}</p>
            <p className={styles.price}>{price}</p>
            <p className={styles.location}>{location}</p>
        </div>

class cat lib for conditional modifications of styles

import cc from 'classcat'; // import with npm first
...
    const styleTitle = cc({
        [styles.title]: true,
        [styles.isSold]: isSold
    });

adding event handlers and use state

import {useState} from 'react';
import React from "react";
import styles from './NavigationBar.module.css';

export const NavigationBar = () => {

    const leftButtonValue = '<';
    const rightButtonValue = '>';

    const [myName, setMyName] = useState(0);

    const handleRightClick = (e) => {
        setMyName(myName + 1);
        console.log(myName);
    }

    return (
        <div className={styles.navigation}>
            <progress className={styles.progress} value="0" max="100"></progress>

            <button className={styles.buttons__left} >
                {leftButtonValue}
            </button>
            <button className={styles.buttons__right} onClick={handleRightClick} >
                {rightButtonValue}
            </button>
        </div>
    );
}
Posted in Без рубрики | Leave a comment

Js. New way of creating methods in objects

// lets say we have some object here
let range = {
    from: 1,
    to: 5
}

range['anyMethod'] = function(){
    return 'hi from new way of creating method';
}

console.log(range.anyMethod());

// lets do the iteration from 1 to 5

range[Symbol.iterator] = function () {
    return {
        current: this.from,
        last: this.to,
        next() {
            if (this.current <= this.last) {
                return {done: false, value: this.current++}
            } else
                return {done: true}
        }
    }
}

// now let's iterate
for (let num of range){
    console.log(num)
}


Posted in Без рубрики | Comments Off on Js. New way of creating methods in objects

HTML.CSS.BoxModel

Here is the box model

this will squeze box to definite size, for example 300 px width

box {
  width: 300px;
  box-sizing: border-box;
}

And this will set content width to 300 px

box {
  width: 300px;
  box-sizing: content-box;
}

There is a star selector that applies css rule to every element

* {
   box-sizing: content-box;
}

Horizontal margins are summed, Vertical margins are combined (from 30 px. and 20 px. will be chosen 30 px., the biggest)

Posted in Без рубрики | Comments Off on HTML.CSS.BoxModel

HTML.CSS.Relative font size

This code will increase font size to 90 px. 3em means multiply to 300 %.

...
<head>
<style>
body {
  font-size: 30px;
}
</style>
</head>
<body>
  <div style="font-size: 3em;">How big am I?</div>
</body>
...

Posted in Без рубрики | Comments Off on HTML.CSS.Relative font size

HTML. CSS. Priority rules

  1. Merge and overriding. Stylesheet (0) – > Style in header (1) -> Style Tag in other tag (2). In embraces the priority of the tag. Same tags will be overriden, other will be merged.
  2. Inheritance. Every children tag inherits css style if defined from the parent. For ex. every <p> tag defined in the body tag will inherit rules for the body.
  3. Specificity. Most specific selector wins. You can count the scores like this

That means that

style in tag > id > class > number of Elements

Posted in Без рубрики | Comments Off on HTML. CSS. Priority rules

HTML. CSS3. Style Placement

There are 3 ways of styling html page

  1. From external file, linking through <link> tag
  2. From <style> tag on the page
  3. From inline <style> tag inside some tag, for example <p>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Style Placement</title>
    <link rel="stylesheet" href="styles.css">
    <style>
        h2 {
            color: maroon;
        }
    </style>
</head>

<body>
<h1>Style Placement</h1>
<h2>Subheading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex et similique cupiditate dignissimos delectus nulla dolore, eos dolorum quidem excepturi, facere non repellat accusamus, atque? Id voluptate eos et accusantium.</p>
<h2>Subheading</h2>
<p style="text-align: center">I am centered</p>
</body>
</html>
Posted in Без рубрики | Comments Off on HTML. CSS3. Style Placement

Delphi. Simple helper

Что такое хэлпер, можно прочитать здесь. Если кратко, то это класс расширяющий функциональность другого класса. Это немного похоже на наследование, но синтаксически выглядит по-другому, а именно:

type
  THelperForTObject = class helper for TObject
  public
    procedure Log(aMsg: string);
  end;

implementation

{ THelperForTObject }

procedure THelperForTObject.Log(aMsg: string);
begin
  Write(aMsg);
end;

Теперь мы можем в любом классе вызывать логгер, не правда ли удобно?

  o := TObject.Create();
  try
    o.Log('test logging');
    ReadLn;
  finally
    o.Free();
  end;

Области применения хэлперов.

Posted in Без рубрики | Comments Off on Delphi. Simple helper