Skip to content
Advertisement

React run javascript code after all render is completed in function based component

I had a form component with the following content

function Form() {
    return (
    <div className="form-container">
        <div className="form-control">
            <label id="text-input">Text </label>
            <input type="text"></input>
        </div>
        <div className="form-control">
            <label>Time </label>
            <input type="text"></input>
        </div>
        <div className="form-control" style={{alignItems:"center"}}>
            <button className="add-but">Add</button>
        </div>
    </div>
    )
}

I wanted to focus the text element after the component gets rendered.
I was first trying to put {document.querySelector("#txt-in").focus()}, it didn’t work and after searching I found I could use the tag autoFocus. and everything would work beautifully.

But I was wondering, what if I want to actually execute javascript code after rendering? or actually do this in javascript? I found answers for class based components but couldn’t find for function based components like the one I am using.

how do I execute code I want executed after the element is rendred, in function based components?

Advertisement

Answer

You can use React Hooks useEffect for your purpose.

Simply put below code

import React, {useEffect} from "react";

function Form() {

 useEffect(() => {
    // Do whatever you want after first render
    // Put your code here
 }, [])

}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement