2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

入力文字の行数で縦幅が可変するtextareaのReactコンポーネント

Last updated at Posted at 2021-02-20

概要

次の記事を参考に入力文字の行数で縦幅が可変するReactコンポーネントを作成しました
react hook formがすぐに使いたかったのでforwordRefを使用して実装しています

TypeScriptのコード

import { ComponentProps, forwardRef, useRef } from "react"

export const FlexTextArea = forwardRef<HTMLTextAreaElement, ComponentProps<"textarea">>(
  (props, ref) => {
    const dummyRef = useRef<HTMLDivElement>(null)

    return (
      <div className={"flex_text_area"}>
        <div className={"flex_text_area_dummy"} aria-hidden={true} ref={dummyRef} />
        <textarea
          {...props}
          ref={ref}
          onChange={(e) => {
            if (dummyRef.current) {
              dummyRef.current.textContent = e.target.value + "\u200b"
            }
            if (props.onChange) {
              props.onChange(e)
            }
          }}
        />
      </div>
    )
  },
)

スタイル(less)

.flex_text_area {
    position: relative;

    .flex_text_area_dummy {
        overflow: hidden;
        visibility: hidden;
        box-sizing: border-box;
        padding: 5px 15px;
        min-height: 120px;
        white-space: pre-wrap;
        word-wrap: break-word;
        overflow-wrap: break-word;
        border: 1px solid;
    }

    & > textarea {
        position: absolute;
        top: 0;
        left: 0;
        box-sizing: border-box;
        padding: 5px 15px;
        width: 100%;
        height: 100%;
        background-color: transparent;
        border: 1px solid #b6c3c6;
        border-radius: 4px;
        color: inherit;
        font: inherit;
        letter-spacing: inherit;
        resize: none;
    }
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?