Kinda Code
Home/React/React + TypeScript: Create an Autosize Textarea from scratch

React + TypeScript: Create an Autosize Textarea from scratch

Last updated: March 03, 2023

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 this command:

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 = () => {
  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.

Conclusion

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 category page and React Native category page for the latest tutorials and examples.

Related Articles