[React] chapter_05

DEVELOPERS_Ivan ㅣ 2023. 8. 31. 17:45

더보기
// TODO : 부모 컴포넌트 메인 : App.js
// TODO : 리액트에서 처음으로 실행되는 js(최상위 부모 컴포넌트)
// TODO : 웹브라우저 확인(주소창) : http://localhost:3000
 
// TODO : App.css import (기본 : 중앙정렬)
import "./App.css";
 
// TODO : 자식 컴포넌트 가져오기(import)
import A_Accommodate from "./pages/A_Accommodate";
import A_Accommodate_Exam from "./pages/A_Accommodate_Exam.js";
import A_Accommodate_Exam2 from "./pages/A_Accommodate_Exam2.js";
import D_ConfirmButton from "./pages/D_ConfirmButton";
import E_ConfirmButton_Exam from "./pages/E_ConfirmButton_Exam";
import F_ConfirmButton_Exam2 from "./pages/F_ConfirmButton_Exam2";
import G_LandingPage from "./pages/G_LandingPage";
import H_Book from "./pages/H_Book";
 
function App() {
  // TODO : 변수/함수를 정의하는 부분
  // TODO : 화면에 보이는 부분 : return 안에 있는 html 태그 화면에 보임
  return (
    <div className="App">
      {/* TODO: 자식 컴포넌트 추가 */}
      <A_Accommodate />
      {/* <A_Accommodate_Exam /> */}
      {/* <A_Accommodate_Exam2 /> */}
      {/* <D_ConfirmButton /> */}
      {/* <E_ConfirmButton_Exam /> */}
      {/* <F_ConfirmButton_Exam2 /> */}
      {/* <G_LandingPage /> */}
      {/* <H_Book /> */}
    </div>
  );
}
 
export default App;
더보기
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.
 
      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
    <!-- TODO : 부트스트랩 css 삽입 bootstrap css cdn -->
    <link
      rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
      crossorigin="anonymous"
    />
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.
 
      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.
 
      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>


A_Accommodate
&&(논리연산자) 이용하여
입장 및 감소 버튼 클릭 시 실시간 화면으로 count 변수 1씩 증, 감소 보여주기
isFull && (.....)
더보기

 

// A_Accommodate.js : 자식 컴포넌트
// rfce
// TODO: 리액트의 조건문 : 1) 논리연산자(&&)  2) 3항 연산자
import React, {useState} from 'react'
import "../assets/styles.css";
 
function A_Accommodate() {
    // TODO: 변수 정의
    // 사용법 : let [변수명, set변수명] = useState(초기값);
    let [isFull, setIsFull] = useState(true);
    // 카운트 변수
    let [count, setCount] = useState(0);
 
    // TODO: 함수 정의
    // nfn
    const increaseCount = () => {
        // count 변수 1씩 증가시키기
        let tmpVal = count + 1; // 1 증가
        // count setter 함수 넣기(변수 값 변경(수정))
        setCount(tmpVal);
     }
 
    //  if/for문 못씀 : JSX 표현식{}에서 못씀
    // 함수안에서 가능
    //  감소 함수
    // nfn
    const decreaseCount = () => {
        // count 변수 1씩 감소시키기 , 단, 음수제외
        if(count > 0) {
            let tmpVal = count - 1; // 1 감소
            // count setter 함수 넣기(변수 값 변경(수정))
            setCount(tmpVal);
        }
     }
 
  return (
    <div>
        {/* count 변수 화면 출력 */}
        <p>{`총 ${count} 명을 수용했습니다.`}</p>
 
        {/* 증가버튼 */}
        <button className='btn btn-primary'
                onClick={increaseCount}
        >입장</button>
        <br/>
 
        {/* TODO: 감소버튼 : 음수값이 나오면 안됨(최소값 : 0) */}
        <button className='btn btn-warning'
                onClick={decreaseCount}
        >퇴장</button>
 
        {/* TODO: isFull 참이면 && 실행문(태그) : 실행문이 화면에 보임 */}
        {/*              거짓이면 실행문(태그) 화면에 안보임 */}
        {
            isFull &&
                // 사용법 : <태그 style={{속성: "값"}} >
                <p style={{ color: "red"}}>정원이 가득찼습니다.</p>
        }
    </div>
  )
}
 
export default A_Accommodate

감소버튼 : 음수값이 나오면 안됨(최소값 : 0)  /  정원이 가득찼습니다. 는 화면에 계속 보이는 상황

더보기
// A_Accommodate.js : 자식 컴포넌트
// rfce
// TODO: 리액트의 조건문 : 1) 논리연산자(&&)  2) 3항 연산자
import React, { useState } from "react";
import "../assets/styles.css";

 

function A_Accommodate() {
  // TODO: 변수 정의
  // 사용법 : let [변수명, set변수명] = useState(초기값);
  let [isFull, setIsFull] = useState(true);
  // 카운트 변수
  let [count, setCount] = useState(0);

 

  // TODO: 함수 정의
  // nfn
  const increaseCount = () => {
    // count 변수 1씩 증가시키기
    let tmpVal = count + 1; // 1 증가
    // count setter 함수 넣기(변수 값 변경(수정))
    setCount(tmpVal);
  };

 

  //  if/for문 못씀 : JSX 표현식{}에서 못씀
  // 함수안에서 가능
  //  감소 함수
  // nfn
  const decreaseCount = () => {
    // count 변수 1씩 감소시키기 , 단, 음수제외
    if (count > 0) {
      let tmpVal = count - 1; // 1 감소
      // count setter 함수 넣기(변수 값 변경(수정))
      setCount(tmpVal);
    }
  };

 

  return (
    <div>
      {/* count 변수 화면 출력 */}
      <p>{`총 ${count} 명을 수용했습니다.`}</p>

 

      {/* 증가버튼 */}
      <button className="btn btn-primary" onClick={increaseCount}>
        입장
      </button>
      <br />

 

      {/* TODO: 감소버튼 : 음수값이 나오면 안됨(최소값 : 0) */}
      <button className="btn btn-warning" onClick={decreaseCount}>
        퇴장
      </button>

 

      {/* TODO: isFull 참이면 && 실행문(태그) : 실행문이 화면에 보임 */}
      {/*              거짓이면 실행문(태그) 화면에 안보임 */}
      {/* count가 3 보다 크거나 같을 때 "정원이 가득찼습니다." 메시지 출력 */}
      {count >= 3 && <p style={{ color: "red" }}>정원이 가득찼습니다.</p>}
    </div>
  );
}

 

export default A_Accommodate; 
A_Accommodate_Exam
&&(논리연산자) 이용하여
아래 노란버튼을 클릭하면 파란버튼이 보이게 하기
isButton  && 
변수 && 실행문(태그)  (변수가 참이면 실행문(태그)이 보이고 , 아니면 실행문(태그)이 안보임)
더보기
// A_Accommodate_Exam.js : 자식(연습)
// rfce
// TODO: 연습문제 : 아래 노란버튼을 클릭하면 파란버튼이 보이게 하세요
// 힌트 : &&(논리연산자)
//       변수 && 실행문(태그)  (변수가 참이면 실행문(태그)이 보이고 , 아니면 실행문(태그)이 안보임)
import React, {useState} from 'react'
 
function A_Accommodate_Exam() {
 
  // TODO: 변수 정의
  // 사용법 : let [변수명, set변수명] = useState(초기값);
  let [isButton, setIsButton] = useState(false); // false
 
  // TODO: 함수 정의
  // nfn : 클릭 함수
  const blueClick = () => {
    // isButton : false -> true : setIsButton(변경될값);
    setIsButton(true);
   }
 
  return (
    <div>
      <button onClick={blueClick} className="btn btn-warning">
        노란 버튼
      </button>
      <br/>
      {
        isButton &&
          <button className="btn btn-primary">
            파란 버튼
          </button>
      }
    </div>
  )
}
 
export default A_Accommodate_Exam

A_Accommodate_Exam2
&&(논리연산자) 이용하여
버튼을 클릭하면 isTable 변수의 값을 true 로 바꾸고,  아래 내용을 담고 있는 테이블 태그로  화면 보이게 하기
부트스트랩 테이블 디자인 이용
isTable && (...)
더보기
// A_Accommodate_Exam2.js : 자식(연습)
// rfce
// TODO : 연습문제 ) 아래 소스를 완성하세요
//   버튼을 클릭하면 isTable 변수의 값을 true 로 바꾸고,
//   아래 내용을 담고 있는 테이블 태그로
//   화면에 보이게 만드세요.
//   (부트스트랩 테이블 디자인을 활용하세요.)
//    테이블 내용 :
//               No   Dname       Loc
//               1    Sales       부산
//               2    Development 서울
import React,{useState} from "react";

function A_Accommodate_Exam2() {
  // TODO: 변수 정의
  // 사용법 : let [변수명, set변수명] = useState(초기값);
  let [isTable, setIsTable] = useState(false);

  // TODO: 함수 정의
  // nfn
  // 클릭 함수
  const blueClick = () => {
    // isTable : false -> true , setIsTable(변경값)
    setIsTable(true);
  };

  return (
    <div>
      <button onClick={blueClick} className="btn btn-warning">
        테이블 보이기
      </button>
      <br />
      {/* {변수 && 태그} : 변수(참) 태그가 보임 */}
      {/* 자동정렬 : ctrl + alt + l */}
      {isTable && (
        <table class="table">
          <thead>
            <tr>
              <th scope="col">No</th>
              <th scope="col">Dname</th>
              <th scope="col">Loc</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <th scope="row">1</th>
              <td>Sales</td>
              <td>부산</td>
            </tr>
            <tr>
              <th scope="row">2</th>
              <td>Development</td>
              <td>서울</td>
            </tr>
          </tbody>
        </table>
      )}
    </div>
  );
}

export default A_Accommodate_Exam2;

D_ConfirmButton
((조건식)? "true" : "false" ) 3항 연산자를 이용하여
버튼 클릭 활성화  & 비활성화 시키기
3항 연산자 사용법 : 
사용법 : (조건식)? "true" : "false"
더보기
// D_ConfirmButton.js : 자식 컴포넌트
// rfce
// TODO: 리액트의 조건문 : 2) 3항 연산자를 사용
import React, { useState } from "react";

function D_ConfirmButton() {
  // TODO: 변수 정의
  let [isConfirmed, setIsConfirmed] = useState(false);

  // TODO: 함수 정의
  // nfn
  const handleConfirm = () => {
    // 클릭하면 isConfirmed ( false -> true )
    setIsConfirmed(true);
  };

  return (
    <div>
      {/* 예제 : 아래 버튼 클릭하면 문구 : 확인됨 -> 확인하기, 상태(비활성화)
                                   disabled=false(활성화)[true(비활성화)]
         */}
      <button onClick={handleConfirm} disabled={isConfirmed}>
        {/* 3항 연산자 사용 */}
        {/* 사용법 : (조건식)? "true" : "false" */}
        {isConfirmed === true ? "확인됨" : "확인하기"}
      </button>
    </div>
  );
}

export default D_ConfirmButton;

버튼 클릭하면 문구 : 확인됨 -> 확인하기, 상태(비활성화) / disabled=false(활성화)[true(비활성화)

E_ConfirmButton_Exam
((조건식)? "true" : "false" ) 3항 연산자를 이용하여
변수에 값을 이용한 정원 및 입장 가능 표현하기
isFull  ===  true  ? 
더보기
// TODO : 자식 컴포넌트 연습 E_ConfirmButton_Exam.js

// TODO : 연습문제
// 아래 변수에 값이 있다. isFull 이 true 이면
// <p style={{ color: "red" }}>정원이 가득찼습니다.</p>
//   아니면
// <p style={{ color: "blue" }}>입장할 수 있습니다.</p>
//  를 출력하세요.

// TODO : 리액트 기본 컴포넌트 템플릿 단축키 : rfce
// TODO : import 함수 제대로 에러 확인 필수
import React, { useState } from "react";

function E_ConfirmButton_Exam() {
  // TODO : 변수 정의
  let [isFull, setIsFull] = useState(false);

  // TODO : 변수 정의 : 클릭 (isFull:false -> true)
  // nfn
  const HeaderleConfirm = () => {
    // (isFull:false -> true), setter 함수 : setIsFull(변경값)
    setIsFull(true);
  };
  return (
    <div>
      <button onClick={HeaderleConfirm} className="btn btn-warning">
        {
          /* 힌트 */
          isFull === true ? (
            <p style={{ color: "red" }}>정원이 가득찼습니다.</p>
          ) : (
            <p style={{ color: "blue" }}>입장할 수 있습니다.</p>
          )
        }
      </button>
    </div>
  );
}

F_ConfirmButton_Exam2
((조건식)? "true" : "false" ) 3항 연산자를 이용하여
변수에 값을 이용한 정원 및 입장 가능 표현
count > 10 === true ? true : false
더보기
// TODO : 자식 컴포넌트 연습 E_ConfirmButton_Exam.js

// TODO : 연습문제
// 아래 변수 count 에 9 의 값이 있다.
//  10을 초과하면 ( count>10 )
// <p style={{ color: "red" }}>정원이 가득찼습니다.</p>
//  아니면 <p style={{ color: "blue" }}>입장할 수 있습니다.</p> 를 출력하세요.

// TODO : 리액트 기본 컴포넌트 템플릿 단축키 : rfce
// TODO : import 함수 제대로 에러 확인 필수
import React, { useState } from "react";

function F_ConfirmButton_Exam2() {
  // TODO : 변수 정의
  let [count, setCount] = useState(9); // 카운트 9
  // TODO : 함수 정의
  // nfn
  // 클릭하면 카운팅 : 1증가
  const handleConfirm = () => {
    let tmpVal = count + 1;
    setCount(tmpVal);
  };

  return (
    <div>
      현재 정원 : {count} {/* TODO: 카운트 9 */}
      <br />
      {/* count > 10 비활성화(true) */}
      <button
        onClick={handleConfirm}
        disabled={count > 10 === true ? true : false}
      >
        {count > 10 === true ? (
          // true 일 때
          <p style={{ color: "red" }}>정원이 가득찼습니다.</p>
        ) : (
          // false 일 때
          <p style={{ color: "blue" }}>입장할 수 있습니다.</p>
        )}
      </button>
    </div>
  );
}

export default F_ConfirmButton_Exam2;

<button onClick={handleConfirm} disabled={count > 10 === true ? true : false} >

G_LandingPage
((조건식)? "true" : "false" ) 3항 연산자를 이용하여
로그인& 로그아웃 토글 표현하기
isLoggedIn === true ?
더보기
// TODO : 자식 컴포넌트 연습 G_LandingPage.js

// TODO : 삼항 연산자를 이용한 로그인& 로그아웃 토글
// 아래 내용을 확인하고 아래 코딩하세요 부분을 코드 완성하세요
// onClickLogout 함수는 클릭하면
// isLoggedIn 변수의 값을 false -> true 로 변경한다.

// onClickLogin 함수는 클릭하면
// isLoggedIn 변수의 값을 true -> false 로 변경한다.

// TODO : 리액트 기본 컴포넌트 템플릿 단축키 : rfce
// TODO : import 함수 제대로 에러 확인 필수
import React, { useState } from "react";

function G_LandingPage() {
  // TODO : 변수 정의
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  // TODO : 함수 정의
  // nfn
  const onClickLogin = () => {
    // TODO 아래 코딩하세요
    // TODO isLoggedIn 변수의 값을 false -> true 로 변경한다.
    setIsLoggedIn(true);
  };
  // nfn
  const onClickLogout = () => {
    // TODO 아래 코딩하세요
    // TODO isLoggedIn 변수의 값을 true -> false 로 변경한다.
    setIsLoggedIn(false);
  };

  return (
    <div>
      {isLoggedIn === true ? (
        <button onClick={onClickLogout}>로그아웃</button>
      ) : (
        <button onClick={onClickLogin}>로그인</button>
      )}
    </div>
  );
}

export default G_LandingPage;

<div> {isLoggedIn === true ? (<button onClick={onClickLogout}>로그아웃</button>) : (<button onClick={onClickLogin}>로그인</button>)} </div>

H_Book
반복문 완성하기(ul-li(반복)), 부트스트랩, 화면에 name 출력
사용법 : 배열변수.map((value, index)=>{return (태그))})
더보기
// TODO : 자식 컴포넌트 연습 H_Book.js

// TODO : 반복문 완성하기(ul-li(반복)), 부트스트랩, 화면에 name 출력하세요
// TODO : 사용법 : 배열변수.map((value, index)=>{return (태그))})

// TODO : 리액트 기본 컴포넌트 템플릿 단축키 : rfce
// TODO : import 함수 제대로 에러 확인 필수
import React from "react";

function H_Book() {
  // TODO : 변수 정의

  const students = [
    {
      id: 1,
      name: "Inje",
    },
    {
      id: 2,
      name: "Steve",
    },
    {
      id: 3,
      name: "Bill",
    },
    {
      id: 4,
      name: "Jeff",
    },
  ];

  // TODO : 함수 정의
  // nfn

  {
    /* 부트스트랩에서 코드 복사함 */
  }
  return (
    <div>
      <ul class="list-group">
        {/* map() 특징 : 배열의 개수(길이)만큼 자동 반복됨(0 ~ 3 : 인덱스번호도 자동증가) */}
        {/* 반복문 : 여기서 돌리면 됨 : students.map((student, index)=>{return (<li>{student.속성}</li>)})  */}
        {/* 반복문 : 여기서 돌리면 됨 : students.map((student, index)=>(<li>{student.속성}</li>))  */}
        {/* 사용법 : 배열변수.map((value, index(생략), array(생략))=>{반복문;}); */}
        {students.map((student, index) => (
          <li class="list-group-item" key={index}>
            {student.name}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default H_Book;

'Visual Studio Code' 카테고리의 다른 글

[React] chapter_07  (0) 2023.09.01
[React] chapter_06  (0) 2023.08.31
[React] chapter_04  (0) 2023.08.30
[React] chapter_03  (0) 2023.08.30
[React] 04_chapter 02  (0) 2023.08.29