Answer the question
In order to leave comments, you need to log in
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
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;
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 questionAsk a Question
731 491 924 answers to any question