Home > Net >  how to dinamically resize a textarea in react
how to dinamically resize a textarea in react

Time:08-26

I'm trying to change the size of a textarea with the text. The code is working but for any reason that I don't get, the textarea resizes with the first letter I stroke and then works propertly. Any idea what is causing this weird first resizing?

This is the code I have in the app.js in a recently created project.

import './App.css';

function App() {

  function handleKeyDown(e) {

    e.target.style.height = 'inherit';
    e.target.style.height = `${e.target.scrollHeight}px`;

  }

  return (

    <div>
      <header className="App-header" style={{
         display: 'flex',
         justifyContent: 'center',
         width: '470px',
         backgroundColor: '#fff',
         borderRadius: '5px',
         padding: '25px 25px 30px'
          }} >
        <div>
          <textarea onChange={handleKeyDown} style={{
            width: '95%',
            padding: '15px',
            borderRadius: '5px',
            outline: 'none',
            resize: 'none'
          }} />
        </div>
      </header>
    </div>)
;}

export default App;

Any idea what is causing this weird first resizing? Maybe there is something I'm missing, any clue can help.

Thanks.

CodePudding user response:

You need to add a hook that runs code once the DOM is first loaded and then also make the height change there.

However id recommend just using a library for this https://github.com/Andarist/react-textarea-autosize

import React, { useLayoutEffect, useRef } from "react";

function App() {
  const textbox = useRef(null);

  function adjustHeight() {
    textbox.current.style.height = "inherit";
    textbox.current.style.height = `${textbox.current.scrollHeight}px`;
  }

  useLayoutEffect(adjustHeight, []);

  function handleKeyDown(e) {
    adjustHeight();
  }

  return (
    <div>
      <header
        className="App-header"
        style={{
          display: "flex",
          justifyContent: "center",
          width: "470px",
          backgroundColor: "#fff",
          borderRadius: "5px",
          padding: "25px 25px 30px"
        }}
      >
        <div>
          <textarea
            ref={textbox}
            onChange={handleKeyDown}
            style={{
              width: "95%",
              padding: "15px",
              borderRadius: "5px",
              outline: "none",
              resize: "none"
            }}
          />
        </div>
      </header>
    </div>
  );
}

export default App;

  • Related