[Web Programming] 6. useState 활용하기

백서진·2023년 4월 13일
0

1. 활용 1

user를 state로 만들고 props 전달시켜서 렌더링 시키기

// App.js

// 1.
// Header Component를 만드세요.
// header tag, p tag
// Current user: {user}


// 2.
// Body Component를 만드세요
// section tag, h1 tag
// Welcome back! {user}
// {user} state로 만들고 props 전달시켜서 렌더링 시키기

import "./styles.css";
import Header from "./components/Header";
import Body from "./components/Body";
import { useState } from "react";

export default function App() {
  const [user, setUser] = useState("아저씨");

  return (
    <div className="App">
      <Header user={user} />
      <Body user={user} />
    </div>
  );
}
// Header.js

export default function Header(props) {
  return (
    <header>
      <p>Current user : {props.user}</p>
    </header>
  );
}
// Body.js

export default function Body(props) {
  return (
    <section>
      <h1>Welcome back! {props.user}</h1>
    </section>
  );
}

활용 1 결과

props.user아저씨가 렌더링되었다!


2. 활용 2

1. boxes에 있는 정보를 이용해서 on인 애들은 배경 검은 색 만들고 아닌 애들은 흰색 만들기

2. box 클릭하면 색깔 토글시키기

// App.js

// 1.
// boxed에 있는 배열 들고와서
// div 태그로 만들기
// css를 이용해서 외곽이 검은색 1px이고
// 백그라운드가 투명인 100px 100px 짜리 정사각형 렌더링 시키기

// 2.
// boxes에 있는 정보를 이용해서 on인 애들은
// 배경 검은 색 만들고 아닌 애들은 흰색 만들기

// 3. box 클릭하면 색깔 토글시키기

// 4.
// 어떻게 정의해야 state에 특정 id를 가진 square의 on 값을 바꿀 수 있을까?
// boxes는 오브젝트로 된 배열
// 반복자 안에 반복자
// prev는 오브젝트 하나하나를 지칭한다.
// 그러면 오브젝트 중에 정확히 하나만 골라서 on값을 바꿔야 함

import "./styles.css";
import { useState } from "react";
import boxes from "./boxes";
import Box from "./Box";

export default function App() {
  const [squares, setSquares] = useState(boxes);

  function toggle(id) {
    setSquares((prev) => {
      return prev.map((square) => {
        return square.id === id ? { ...square, on: !square.on } : square;
      });
    });
  }

  const squaresElements = squares.map((square) => (
    <Box on={square.on} key={square.id} id={square.id} toggle={toggle} />
  ));

  return <main>{squaresElements}</main>;
}
// Box.js

import { useState } from "react";

export default function Box(props) {
  const [on, setOn] = useState(props.on);

  const styles = {
    backgroundColor: props.on ? "#222222" : "transparent"
  };
  return (
    <div
      style={styles}
      className="box"
      onClick={() => props.toggle(props.id)}
    ></div>
  );
}
// boxes.js

export default [
  {
    id: 1,
    on: true
  },
  {
    id: 2,
    on: false
  },
  {
    id: 3,
    on: true
  },
  {
    id: 4,
    on: true
  },
  {
    id: 5,
    on: false
  },
  {
    id: 6,
    on: false
  }
];
/* style.css */

* {
  box-sizing: border-box;
}

.box {
  height: 100px;
  width: 100px;
  border: 1px solid black;
  display: inline-block;
}

활용 2 결과

boxes의 on이 true or false이냐에 따라 색이 다른 것을 볼 수 있다.

또한 box를 클릭하면 색이 변한다!


첫 번째 박스를 클릭하니 색이 검은색에서 흰색으로 변했다!


3. 활용 3

안 읽은 메세지 개수 출력

// App.js

// messages는 안읽은 메세지들이다.
// 안읽은 메세지들이 2개 이상이면
// You have ?? unread messages
// 안읽은 메세지가 1개면
// You have a unread message
// 다 읽었으면
// You're all caught up!
// 조건부 렌더링

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [messages, setMessages] = useState(["안녕", "뭐해?", "이명재"]);

  return (
    <div className="App">
      {messages.length === 0 ? (
        <h1>You're all caught up!</h1>
      ) : (
        <h1>
          You have {messages.length} unread{" "}
          {messages.length > 1 ? "messages" : "message"}!
        </h1>
      )}
    </div>
  );
}

활용 3 결과

안녕? / 뭐해? / 이명재 를 읽지 않았으니 You have 3 unread messages가 출력된다!


0개의 댓글

관련 채용 정보