Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get element of component without using listener such as onChange?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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" />
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading