[React] 부모 자식 컴포넌트 props 사용 textarea 만들기

권슬기·2023년 5월 30일
0

react

목록 보기
2/17

(React에 tailwind css 적용)

--부모 컴포넌트--
function Test() {
  return (
    <>
        <div>
            <Textarea maxLength="200" rows="3"/>
        </div>
    </>
  );
}

Test라는 부모 컴포넌트에서 Textarea 컴포넌트로 props maxLength와 row를 전달.

import React, { useState } from "react";

function Textarea({maxLength, rows}) {
  const [InputCount, setInputCount] = useState(0);

  const handleInput = (e: ChangeEvent<HTMLTextAreaElement>) => {
    if (e.target.value.length > maxLength) {
      e.target.value = e.target.value.slice(0, maxLength);
    }
    setInputCount(e.target.value.length);
  };

  return (
    <>
      <textarea onChange={handleInput} maxLength={maxLength} rows={rows} className="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Write your thoughts here..."></textarea>
      <p>
        <span>{InputCount.toLocaleString()}</span>
        <span>/{maxLength}자</span>
      </p>
    </>
    );
}

export default Textarea;

위의 코드를 적용하면 아래처럼 적용이 된다.

profile
병아리 프론트엔드 개발자

0개의 댓글

관련 채용 정보