I would presumably like to run the function auto_grow on useEffect but i require the element to be passed in to edit its values. Is there a way I can pass in the element without a listener so useEffect can make use of it?
I tried document.getElementById but that returns just the textarea and scrollHeight isnt a property.
Code:
function ChatInput(props){
const [text, setText]=useState();
function auto_grow(element){
element.target.style.height = "5px";
console.log(element)
element.target.style.height =(element.target.scrollHeight)+"px";
}
useEffect(()=>{
setText(props.answer)
},[props.answer])
return(
<>
<Container style={{paddingTop:'.5rem'}}>
<InputGroup>
<InputGroup.Text>Bot</InputGroup.Text>
<Form.Control onLoad={auto_grow}style={textareaStyle} as="textarea" value={text} aria-label="Chat Input"/>
</InputGroup>
</Container>
</>
)
}
const textareaStyle = {
resize: "none",
overflow: "hidden",
minHeight: "50px",
maxHeight: "1000px"
}
export default ChatInput;
>Solution :
You can use a ref to get the underlying element.
import { useState, useEffect, useRef } from 'react';
// ...
function ChatInput(props) {
const ref = useRef();
// ref usage example:
useEffect(() => {
ref.current.style.height = ref.current.scrollHeight + 'px';
}, []);
// ...
return (
// other elements...
<Form.Control ref={ref} as="textarea" value={text} aria-label="Chat Input" />
);
}