skip to Main Content

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;

2

Answers


  1. you are mistaken. scrollHeight is a property of each dom element

    var element = document.getElementById('test')
    console.log(element.scrollHeight)
    <body>
    <div id = "test">xxx</div>
    </body>
    Login or Signup to reply.
  2. 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" />
        );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search