Today I Learned (Oct)

GODORI·2018년 10월 28일
12

TIL

목록 보기
1/2
post-thumbnail

Banner made by Banner Maker

Develop Log
2018.10.19 - 2018.10.28

공부했거나 알게 된 내용을 모아서 정리하는 글을 종종 쓰려고 합니다.
영문 작성 연습을 겸하고 있으니 틀린 표현이나 오타가 있다면 편하게 알려주세요 :)

Useful Things


🎨 Code Formatter

  • Recommanded Code Formatter is Prettier
  • Install Prettier Extension (VS Code)
  • Settings(cmd+,) -> Editor tab -> Activate Format On Save
  • Or add "editor.formatOnSave": true to user setting file

🏞 Get Sample Image by URL

Snippet of React & JS


⛏ Simple React Snippets Extension

Create component file as *.jsx
And install extension Simple React Snippets (VS Code)
Then, we can use Snippet Renders

  • Snippet Example:

      imrc	Import React / Component :
      import React, { Component } from 'react';
    
      cc	Class Component :
      class [CLASSNAME] extends Component {
          state = {  }
          render() {
              return (  );
          }
      }
      export default [CLASSNAME];
  • export default [CLASSNAME] and class [CLASSNAME] can be integrated as one line:

        class [CLASSNAME] extends Component { ... }
        export default [CLASSNAME];
    
        => export default class [CLASSNAME] extends Component { ... }

    c.f. Result of code snippet cc is created seperated shape as a default.

📦 Fragment (React v16)

Use <Fragment> instead of <div>.
Fragment let you group a list of children without adding extra nodes (ex. div tag)
Then, there is no need to return div and rendered html element has no <div> tag also.

  • Using Fragment Example:

    render() {
        return (
        <React.Fragment>
            <h1>Hello world</h1>
            <button>Button</button>
        </React.Fragment>
        );
    }
  • Rendering result :

      <!-- not use Fragment -->
      <div>
        <h1>Hello world</h1>
        <button>Button</button>
      </div>
    
      <!-- use Fragment -->
      <h1>Hello world</h1>
      <button>Button</button>

💎 Basic Boolean Check in JS for React

There are two values of boolean. When you check the value, they means respectively like
- falsy : STOP THERE!!
- truthy : CONTINUE!!

  • In Javascript, string and number is truthy (numbers except 0)

    true && false; // false
    
    true && "Hi"; // "Hi"
    
    true && "Hi" && 1; // 1
  • That's why expression in return result is Plain Text "Please create a new tag!"

    state = { tags: [] }
    
    render() {
        return ({ this.state.tags.length === 0 && "Please create a new tag!"; })
    }

📌 About this.state in React

In obj.method() : this is a reference of the object
In function() : this is a reference of the window

  • If you want to change the state in method, you would get a message of this is undefined!

    class Counter extends Component {
      state = { count : 0}
    
      handleIncrement() {
          console.log(this.state); // this is undefined!
      }
      ...
    }

    First Solution:
    Add constructor and bind method.
    With bind method, we can set value of this.

    constructor(){
        super();
        this.handleIncrement = this.handleIncrement.bind(this);
    }
    
    handleIncrement() {
        console.log(this);
    }

    Second Solution :
    Use arrow function =>
    Arrow function don't rebind this. Clean and fast!

    handleIncrement = () => {
      console.log(this);
    };

🐛 Debugging React Apps

  • Install Chrome / FF extension "React Developer Tools"
  • $r -> Can check the component and element easily!
  • It is not only for debugging React element, but also for checking common HTML pages

🐔 Remove Local State from Components

Controlled Component dosen't have local states.
It receives all the data by a props and raise events whenever data need to be change.
And remove all of this.state.** from the code

  • AS-IS

    handleIncrement = () => {
      this.setState({ value: this.state.value + 1 });
    };
    
    // * Inside of render ()
    <button onClick={this.handleIncrement} className="...">Inc</button>;
  • TO-BE

    // * Remove handleIncrement()
    // handleIncrement = () => {
    //   this.setState({ value: this.state.value + 1 });
    // };
    
    // * Inside of render ()
    <button
      onClick={() => this.props.onIncrement(this.props.conter)}
      className="..."
    >Inc</button>
profile
잡식개발

5개의 댓글

comment-user-thumbnail
2018년 11월 1일

잘봤습니다~ 앞으로도 좋은 글들 기대할게요~

1개의 답글
comment-user-thumbnail
2018년 11월 2일

내용 좋아요!~ 얼마전부터 React.Fragment 가 <> </> 로도 가능해요. 별거아닌데 사용하다보니 편리하고 좋더라구요. picsum.photos 도 몰랐는데 개발할테 유용할거 같아요. 같은 사이즈 사진구하는것도 많아지면 일이라..ㅎㅎ velog 에 subscribe 기능이 얼릉 생기면 좋겠네요.

1개의 답글
comment-user-thumbnail
2018년 12월 19일

감사합니다! 도움이 많이 되었네요~

답글 달기