[React] typing the props / state / form

hellow_coding·2023년 2월 4일

타입스크립트

  • interface로 타입 지정
  • props type와 유사하며 object의 shape을 설명해 준다.
  • interface는 typescript와 코드가 실행되기 전에 확인해준다.

(1) Typescript - interface

interface playerShape{
  name: string;
  age: number;
}

const sayHello = (playerObj: playerShape) => {
  `Hello ${playerObj.name} you are ${playerObj.age}`;
}

sayHello({name:"sujin", age:12});

//const sayHello = ({name, age}: playerShape) => {
//  `Hello ${name} you are ${age}`;
//}

(2) Typing the Props / default props

Circle.tsx

import styled from "styled-components";

// 타입스크립트 - interface로 타입 지정, object shape를 설명

interface CircleProps {
  bgColor: string;
}

// typescript에게 Container가 bgColor을 받을거라 알려주기 - Container은 div때문 <ContainerPorps>
const Container = styled.div<CircleProps>`
  width: 200px;
  height: 200px;
  background-color: ${props => props.bgColor};
  border-radius: 100px;
`;
  
//CircleProps의 타입이 뭔지 component에게 알려주기
function Circle({ bgColor }: CircleProps ) {
  return <Container bgColor={bgColor} />;
}
// function Circle(props: CircleProps ) {
//   return <Container bgColor={props.bgColor} />;
// }

export default Circle;

App.tsx

import Circle from "./Circle";

function App() {
  return (
    <div>
      <Circle bgColor="teal" />  // bgClor -> required
      <Circle bgColor="tomato" />
    </div>

  );
}

export default App;

(3) optional props (borderColor?: string;)

Circle.tsx

import styled from "styled-components";

// 타입스크립트 - interface로 타입 지정, object shape를 설명
// styled-component
interface ContainerProps {
  bgColor: string;
  borderColor: string; // default props
}

// typescript에게 Container가 bgColor을 받을거라 알려주기 - Container은 div때문 <ContainerPorps>
const Container = styled.div<ContainerProps>`
  width: 200px;
  height: 200px;
  background-color: ${props => props.bgColor};
  border-radius: 100px;
  border: 3px solid ${props => props.borderColor};
`;

interface CircleProps {
  bgColor: string;
  borderColor?: string;  // ? optional props
  text?: string;
}
  
function Circle({ bgColor, borderColor, text="default text" }: CircleProps ) {
  return <Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>
            {text}
         </Container>;  // undefine 상태 ?? -> bgColor
}

export default Circle;

App.tsx

import Circle from "./Circle";

function App() {
  return (
    <div>
      <Circle bgColor="teal" borderColor="yellow" /> // text의 기본값인 default text가 입력
      <Circle bgColor="tomato" text="im here"/>
    </div>

  );
}

export default App;

(*) props undefine 상태 - 기본값 지정

1.
function Circle( { bgColor="yellow" } ) {
return <Container bgColor={bgColor}/}
2.
function Circle( { bgColor } ) {
return <Container bgColor={bgColor ?? "yellow"} /}

(4) state

한번 지정한 속성으로 계속 유지된다.

const [value, setValue] = useState<number | string>(0);  // number or string 타입
  setValue(0);
  setValue("0");
  setValue(true);  // 에러

(5) form

event의 타입 지정
React.FormEvent<HTMLInputElement> / React.FormEvent<HTMLFormElement>
form 태그 내에 없다면 -> React.MouseEvent<HTMLInputElement>

App.txs

import { useState } from "react";


function App() {
  const [value, setValue] = useState("");
  // onChange 함수가 InputElement에 의해서 실행될 것이다.
  // event의 타입 지정
  const onChange = (event: React.FormEvent<HTMLInputElement>) => {
    const {
      currentTarget:{value}, 
    } = event;
    setValue(value);
  };

  const onSubmit = (e: React.FormEvent<HTMLFormElement>)=> {
    e.preventDefault();
    console.log("hello", value);
  };
 
  return (
    <div>
      <form onSubmit={onSubmit}>
        <input value={value} onChange={onChange} type="text" placeholder="usename"></input>
        <button>Log in</button>
      </form>
    </div>

  );
}

export default App;

Form event with react+typescript / currentTarget

const onChange = (event: React.FormEvent<HTMLInputElement>) => {
	console.log(event.currentTarget.value);
};

ES6 문법

const value = event.currentTarget.value
const {value} = event.currentTarget
const {currentTarget:{value}} = event // const {currentTarget: {value, tagName,width, id}} = event;

onsubmit
: form 태그 안에서 form전송을 하기 전에 입력된 데이터의 유효성을 체크하기 위해 사용하는 이벤트.

profile
꿈많은 개발자

0개의 댓글