React + TypeScript: Create an Autosize Textarea from scratch

Last updated on August 5, 2021 A Goodman Loading... Post a comment

This article walks you through a complete example of making an autosize (or auto-resize) textarea in a React project that uses TypeScript. We will use modern React with functional components and the following hooks: useState, useEffect, and useRef. The autosize textarea will be created from scratch without using any third-party packages.

The Example

Preview

The height of the textarea depends on the length of the content. The longer the content, the taller the textarea and vice versa.

The Code

1. Create a new React project with TypeScript template by running:

npx create-react-app kindacode_example --template typescript

2. Remove all of the unwanted code in your src/App.tsx (or src/App.ts) and add the following:

// App.tsx
// Kindacode.com
import React, { useState, useEffect, useRef } from "react";

const App: React.FunctionComponent = () => {
  const textareaRef = useRef<HTMLTextAreaElement | null>(null);

  // The value of the textarea
  const [value, setValue] = useState<String>();

  // This function is triggered when textarea changes
  const textAreaChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    setValue(event.target.value);
  };

  useEffect(() => {
    if (textareaRef && textareaRef.current) {
      textareaRef.current.style.height = "0px";
      const scrollHeight = textareaRef.current.scrollHeight;
      textareaRef.current.style.height = scrollHeight + "px";
    }
  }, [value]);

  return (
    <div style={styles.container}>
      <h3>Kindacode.com</h3>
      <textarea
        ref={textareaRef}
        style={styles.textareaDefaultStyle}
        onChange={textAreaChange}
      >
        {value}
      </textarea>
    </div>
  );
};

export default App;

// Just some styles
// Kindacode.com
const styles: { [name: string]: React.CSSProperties } = {
  container: {
    marginTop: 50,
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
  },
  textareaDefaultStyle: {
    padding: 5,
    width: 400,
    display: "block",
    resize: "none",
    backgroundColor: "#eee",
  },
};

3. Run the project and go to http://localhost:3000 to see the result.

Concluison

Together we’ve written an auto-resize textarea in React and TypeScript. If you would like to learn more new and exciting things about modern React, take a look at the following articles:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles