React + TIL

Dev_Sumni·2022년 5월 25일
post-thumbnail

JSX를 사용하는 위치

  • JSX는 .jsx 혹은 .tsx파일이라면 어디서든 사용가능

조건부 rendering

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
    }
    return <GuestGreeting />;
  }

function Greeting(props) {
  return isLoggedIn ? <UserGreeting /> : <GuestGreeting />;
}

JSX 렌더시 무시되는 값

  • component에서 조건문의 false를 요청하면 false가 나오는게 아니고 아무것도 나오지 않게됨
    (원하는 값을 얻고 boolean 값이 화면에 나오는것을 방지하기 위해)

아래 코드를 render하는 경우 어떤 결과가 나오는지 확인

const App = () => {
  return (
    <>
      <div>{[false, null, undefined, true]}</div>
      <div>{false}</div>
      <div>{null}</div>
      <div>{undefined}</div>
      <div>{true}</div>        안의 값들은 화면에 render되지 않음
    </>
  );
}

loop 활용 rendering

key 역할

최적화를 위해 key값이 겹치지 않도록 attribute를 부여하면 error를 해결할 수 있고, side effect를 방지할 수 있다.

🚩

1~100까지 들어있는 array가 있을때, '7의 배수'라는 텍스트를 포함한 button 출력
10의 배수인 경우 출력 x
그 외 숫자가 들어있는 button 출력하기

import React from 'react';
// 1부터 100까지 들어있는 arr
const arr = Array.from(Array(100), (_, i) => i+1);
const App = () => {
return (
<div>
{/* fill here */}
</div>
);
};

export default App;

import React from 'react';

// 1부터 100까지 들어있는 arr
const arr = Array.from(Array(100), (_, i) => i+1);


const App = (props) => {
  return (
  <div>
    {props.arr.map((item, idx) => {
      if (item % 7 === 0) {
        return (
          <button type='button' key={idx}>
            7의 배수
          </button>
        );
      } else if (item % 10 === 0) {
        return null;
      } else {
        return (
            <button type='button' key={idx}>
              {item}
            </button>
          );
        }
      })}
    </div>
  );
};

export default App;

React에서의 Event Handling

  • 실행될 코드를 적는게 아닌 실행될 함수를 전달

🚩

1~100이 들어있는 button 100개를 만들고 버튼을 클릭하면 들어있는 숫자를 alert로 띄워주기

import React from 'react';

// 1부터 100까지 들어있는 arr
const arr = Array.from(Array(100), (_, i) => i+1);


const App = () => {
  return (
    <div>
      {arr.map(item => (
        <button
        type='button'
        key={item}
        onClick={() => {alert(item);}}
        >
          {item}
        </button>
      ))}
    </div>
  );
};

export default App;
  • 고차 함수
    함수가 함수를 return해서 그 함수를 실행하는것
  • Currying
    고차 함수를 저장해놓고 계속해서 이어나가 붙여 쓸 수 있는것
  • 클로저
    변수를 함수 만들때 사용했는데 함수가 메모리상에서 사라질때까지 계속 변수의 값을 메모리상에 들고있는것

🚩

App 컴포넌트에는 key추가, Card 컴포넌트 채워넣기

import React from 'react';

const users = [{
  name: 'kim',
  id: 5,
}, {
  name: 'hello',
  id: 6,
}, {
  name: 'jin',
  id: 7,
}, {name: 'hi',
id: 10,}, {
  name: 'yellow',
  id: 8,
}];

const Card = (props) => {
  return (
  <div>
  </div>
  );
}

const App = () => {
  return (
  <>
  {users.map((user) => <Card user={user} />)}
  </>
  );
};

export default App;

const Card = (props) => {
  return (
  <div>
    id: {props.user.id}<br />    JS영역이기에 {}사용
    name: {props.user.name}
  </div>
  );
}

const App = () => {
  return (
  <>
  {users.map((user) => <Card user={user} key={user.id} />)}
  </>
  );
};
  • 재사용 가능하다고 생각이 든다면 component를 따로 분리하고, 없다면 인라인 작성
  • key를 적기는 하지만 key용도에 따라 사용만 되는거고, prop으로는 전달되지 않음
    (prop이름을 정할때는 key라는 이름은 사용하지 않도록 주의)
    react환경에서 react handler가 받는 이벤트 객체는 js 이벤트 객체와는 조금 다르게 생김
profile
개발 일지 끄적 끄적,,

0개의 댓글