6
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.

ReactでTextareaの高さを可変にする

Posted at

問題点

textareaのstyleにline-heightを指定すると
入力された値が1行の時でも、余分に余白ができてしまった。。。

textareaの高さを入力された行数によって、可変にしたい。

結論

textareaのrow属性を動的に指定して、実現できた。
ezgif.com-gif-maker (1).gif

コード(React_classコンポーネント)

constructor()

constructor(){
    super();
    this.state={
      text:"サンプルテキスト"
    }
}

高さを計算する関数

  • textarea内の改行は\nで取得できる
  • 入力値を\nで分割すれば、改行数が取得できる
calcTextAreaHeight(value){
    let rowsNum = value.split('\n').length;

    return rowsNum
}

render()

<textarea defaultValue={this.state.text} 
                    rows={this.calcTextAreaHeight(this.state.text)} 
                    onChange={e => this.setState({text:e.target.value})} />
6
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
6
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?