import React from 'react';
import Clicker from './Clicker';
import './App.css';

function App() {
  return (
    <div>
      <Clicker />
    </div>
  );
}

export default App;
import React, { Component } from 'react';


class Clicker extends Component {
    constructor(props) {
        super(props);
        this.state = { num: 1 };
        this.genRandom = this.genRandom.bind(this);
    }

    genRandom() {
        //pick rdNum
        let rdNum = Math.floor(Math.random() * 10) + 1;
        //update state
        this.setState({ num: rdNum });
    }

    render() {
        return (
            <div>
                <h1>Number is: {this.state.num}</h1>
                {this.state.num === 7
                    ? < h2 > You Lucky!</h2>
                    : <button onClick={this.genRandom}>Random Number</button>}
            </div >
        );
    }
}

export default Clicker;

'react' 카테고리의 다른 글

More State : data structure and designing state  (0) 2020.06.14
More State : setting state using state  (0) 2020.06.13
STATE vs PROPS  (0) 2020.06.13
React Events!  (0) 2020.06.13
Introducing State  (0) 2020.06.13

STATE vs PROPS

 

* State :   POJO{}    mutable     to store changing component data

- 컴포넌트에 변형되는 데이터를 저장시 선언

 

* props :   POJO{}    mutable     to store component configuration

- 컴포넌트의 구성 저장시 선언

 

 

## State as Props

- parent component passing down its state values as props to stateless child components.

 class CountParent extends Component {
        constructor(props)  {
            super(props);
            this.state = {count:5};
        }
        render() {
            // passing down parent state as a prop
            return (
                <CountChild count={this.state.count} />
            );
        }
    }

 

'react' 카테고리의 다른 글

More State : setting state using state  (0) 2020.06.13
State clicker exercise : who is lucky  (0) 2020.06.13
React Events!  (0) 2020.06.13
Introducing State  (0) 2020.06.13
Props : styling  (0) 2020.06.13

## React Events

- State most commonly changes in direct response to some event.

- Every JSX element has built-in attributes representing every kind of browser event.

- They are camel-cased(ex: onClick).

- They take callback function as event listeners.

import React, { Component } from 'react'

class Button extends Component {
    render() {
        return ( //most of time we don't do one-line function 
            <button onClick={function () { 
            alert('Hey You Clicked Me!'); 
            }}  >
            Click ME!!'
            </button >
        )
    }
}

export default Button;

 

 

 

## [THIS] is back

- but this is undefined!

- Who is calling *handleClick* for us?

    React is, on click

- What is it calling it on?

    It does not remember to call it on our instance

    The method was called "out of context"

- What do we do?

    *.bind* it!

import React, { Component } from 'react'

class BrokenClick extends Component {
    constructor(props) {
        super(props);
        this.state = { clicked: false };
        this.handleClick = this.handleClick.bind(this);//bind를 통해 this와 엮어줌
    }
    handleClick(e) {
        this.setState({ clicked: true });
    }
    render() {
        return (
            <div>
                <h1>{this.state.clicked ? 'Clicked!!' : 'Not Clicked..'}</h1>
                <button onClick={this.handleClick}>Click Me!!</button>
            </div>
        );
    }
}

export default BrokenClick;

'react' 카테고리의 다른 글

State clicker exercise : who is lucky  (0) 2020.06.13
STATE vs PROPS  (0) 2020.06.13
Introducing State  (0) 2020.06.13
Props : styling  (0) 2020.06.13
Props : default props  (0) 2020.06.13

Goals

- Understand the concept of state in web apps

- Learn how to build state in React

- Use events to trigger state changes



 

State in General

- In any advanced web app, the user interface has to be stateful.

    - ex)

    - logged-in users see a different screen

    - click modal or pop-up window

    - section that expand or collapse, instead of clicking "new page"  

* state of the client interface(front-end) is NOT always directly tied to state of the server.  



 

State Changes

- State is designed to constantly change in response to events.

    ## What does state track

    - UI logic - change state of interface ex) modal open for editing profile

    - Business logic - change state of data ex) new messages in my inbox -> this effects how they display

 


# What does state track?
- UI logic

- Business logic

 

 

 

#  CORE REACT CONCEPT

 

    ## Component 

    ### DATA + UI

    - building block of React

    - combine logic (JS) and presentation (JSX)

 

    ## Prop

    - data passed to a component (or found via defalts)

    - immutable; component cannaot change its own props

 

    ## State

    - internal data specific to a component

    - data can be changed over time!



 

## What is React State?

- In React, state is an INSTANCE ATTRIBUTE on a component.

- It is always an object (POJO);{key:value}

 

 

 

## Initial State : React Constructor Function

- state should be initialized as soon as the component is created.

- so, we set it in the constructor function

constructor(props){
        super(props);
        this.state = {
            /* values we want to track */
        };
    }

 

- Constructor takes one argument, PROPS!

- You must call [Super(props)] at start of constructor, which "registers" your class as a React Component

 

import React, { Component } from 'react';


class Game extends Component {
    constructor(props) {
        super(props);// we need super for approaching to props
        this.state = {
            score: 99,
            gameOver: false
        };
    }
    render() {//don't set a state in render part
        return (
            <div>
                <h1>Your Score is : {this.state.score}</h1>
            </div>
        );
    }
}

export default Game;

 

 

 

## Changing State

- DO NOT CHANGE STATES DIRECTLY ex) this.state.num=0;

- [this.setState({stateKey:stateValue})] is the built-in React method of changing a component's state

    ex)

    this.setState({playerName: "Matt", score: "99"});

- Can call in any instance method except the constructor

- Take an object describing the state change

- Patches state obj ; keys that you didn't specify don't change

 

- Asynchronize! ( the component state will be updated eventually, but React controls WHEN the state will actually change, for performance reasons.)

- Components are re-render when states are updeted

import React, { Component } from 'react'

class Rando extends Component {
    constructor(props) {
        super(props);
        this.state = { num: 0 };
        this.makeTimer();
    }

    makeTimer() {
        setInterval(() => {
            let rand = Math.floor(Math.random() * this.props.maxNum);
            this.setState({ num: rand })
        }, 1000);
    }

    render() {
        //everytime num state is changed render is called again, again
        console.log('changing!'); //콘솔에서 확인 가능
        return <h1>{this.state.num}</h1>
    }
}

export default Rando;

 

 

'react' 카테고리의 다른 글

STATE vs PROPS  (0) 2020.06.13
React Events!  (0) 2020.06.13
Props : styling  (0) 2020.06.13
Props : default props  (0) 2020.06.13
Props : looping props  (0) 2020.06.13

1. like usual,  we can stylie React code using css file.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="app.css">
  <title>Styling React</title>
</head>

<body>
  <div id="root"></div>
  <script src="https://unpkg.com/react/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>

  <script src="https://unpkg.com/babel-standalone"></script>
  <script src="Machine.js" type="text/jsx"></script>
  <script src="index.js" type="text/jsx"></script>

  </script>
</body>

</html>

 

2. css code

.Machine{
    border: 2px solid black;
    background: yellow;
}

.win{
    color: teal;
}

.lose{
    color:red;
}

 

3. app component that render Machine.js component.

class App extends React.Component {
	render() {
		return (
			<div>
				<h1>Slot Machines!</h1>
				<Machine
					s1="●"
					s2="●"
					s3="●"
				/>
				<Machine
					s1="●"
					s2="●"
					s3="★"
				/>
			</div>
		);
	}
}

ReactDOM.render(<App />, document.getElementById('root'));

 

4.  we can set winning or losing style using conditional statements in JSX.

class Machine extends React.Component {
    render() {
        const { s1, s2, s3 } = this.props;
        const win = (s1 === s2 && s2 === s3);
        const colors = { fontSize: '50px', backgroundColor: 'white' };

        // 클래스명 다름
        // for 사용 금지
        // in-line styling 에 camel case 씀
        // 클래스명에 조건문 사용도 가능
        return (
            <div className="Machine">
                <label htmlFor="textInput" />
                <p style={colors}>
                    {s1}{s2}{s3}
                </p>
                <p className={win ? 'win' : 'lose'}>
                    {win ? 'win' : 'lose'}
                </p>
            </div>
        );
    }
}

 

'react' 카테고리의 다른 글

React Events!  (0) 2020.06.13
Introducing State  (0) 2020.06.13
Props : default props  (0) 2020.06.13
Props : looping props  (0) 2020.06.13
Props : slot machine exercise  (0) 2020.06.13

 

class App extends React.Component {
	render() {
		return (
			<div>
				<Hello
					to="Ringo"
					from="Paul"
					bangs={4}
				/>
				<Hello
					to="Andy"
				/>
			</div>
		);
	}
}


ReactDOM.render(<App />, document.getElementById('root'));

 

 

 

we can set default props with [static defaultProps] statement.

class Hello extends React.Component {
    static defaultProps = {
        from: 'Anonymous',
        bangs: 1
    }
    render() {
        const props = this.props;
        let bangs = "!".repeat(props.bangs);
        return (
            <div>
                <p>Hello {props.to} from {props.from} {bangs}</p>
            </div>
        );
    }
}​

 

 

-> Ringo get his personal props <Hello /> from paul with 4 bangs,  Andy get default <Hello /> from Anon because we didn't set any personal prop to his <Hello/ > prop.

 

 

 

'react' 카테고리의 다른 글

Introducing State  (0) 2020.06.13
Props : styling  (0) 2020.06.13
Props : looping props  (0) 2020.06.13
Props : slot machine exercise  (0) 2020.06.13
Props : types of props  (0) 2020.06.13

 

class App extends React.Component {
  render() {
    return (
      <div>
        <Friend
          name="Elon"
          hobby={["Dancing", "Drawing", "Singing"]}
        />

        <Friend
          name="Linda"
          hobby={["Piano", "Reading a book", "Gaming"]}
        />
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

 

 

option 1

class Friend extends React.Component {
  render() {
    const { name, hobby } = this.props;
    return (
      <div>
        <h1>{name}</h1>
        <ul>
          {hobby.map(h => <li>{h}</li>)}
        </ul>
      </div>
    );
  }
}

 

 

option 2

class Friend extends React.Component {
  render() {
    const { name, hobby } = this.props;
    const list = hobby.map(h => <li>{h}</li>)
    return (
      <div>
        <h1>{name}</h1>
        <ul>
          {list}
        </ul>
      </div>
    );
  }
}

'react' 카테고리의 다른 글

Props : styling  (0) 2020.06.13
Props : default props  (0) 2020.06.13
Props : slot machine exercise  (0) 2020.06.13
Props : types of props  (0) 2020.06.13
Introducing Props! and more..  (0) 2020.06.13
class App extends React.Component {
	render() {
		return (
			<div>
				<h1>Slot Machines!</h1>
				<Machine
					s1="●"
					s2="★"
					s3="◆"
				/>
				<Machine
					s1="●"
					s2="●"
					s3="●"
				/>
				<Machine
					s1="●"
					s2="★"
					s3="★"
				/>
			</div>
		);
	}
}

ReactDOM.render(<App />, document.getElementById('root'));
class Machine extends React.Component {
    render() {
        const { s1, s2, s3 } = this.props;
        let win = (s1 === s2 && s2 === s3);

        return (
            <div>
                <p>{s1}{s2}{s3}</p>
                <p>{win ? 'win' : 'lose'}</p>
            </div>
        );
    }
}

 

'react' 카테고리의 다른 글

Props : default props  (0) 2020.06.13
Props : looping props  (0) 2020.06.13
Props : types of props  (0) 2020.06.13
Introducing Props! and more..  (0) 2020.06.13
Introducing JSX : basic concept of React layout  (0) 2020.06.13