X
X
xXRustamXx2018-11-29 18:55:35
React
xXRustamXx, 2018-11-29 18:55:35

Is this approach allowed to do textarea-autosize?

This is contrary to the React concept, but I don’t want to connect the library / component that adjusts the field height because of some textarea, when you can do it yourself, I tried to set 2 heights through setState, one by default and the other dynamic, but in vain:

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexprintme, 2020-03-22
@Alexprintme

Something like this:

import React, { useEffect, useRef, useState} from "react";
const defaultStyle = {
    display: "block",
    overflow: "hidden",
    resize: "none",
    width: "100%",
    backgroundColor: "mediumSpringGreen"
};

const AutoHeightTextarea = ({ style = defaultStyle, ...etc }) => {
    const textareaRef = useRef(null);
    const [currentValue, setCurrentValue ] = useState("");

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

    return (
        <textarea
            ref={textareaRef}
            style={style}
            {...etc}
            value={currentValue}

            onChange={e=>setCurrentValue(e.target.value)}
        />
    );
};

export default AutoHeightTextarea;

M
Mikhail Osher, 2018-11-29
@miraage

Theoretically, it is allowed. Is it normal to write like that - in my opinion, no.
I would write something like this.

class Textarea extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {};
    this.onChange = this.onChange.bind(this);
  }

  onChange(e) {
    this.setState({
      height: e.target.scrollHeight
    });
  }
  
  render() {
    const { height } = this.state;

    return (
      <div>
        <textarea 
          name="text"
          style={{ height }}
          placeholder="Autoresize textarea"
          onChange={this.onChange}
        />
      </div>
    )
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question