Abraham
Abraham

Reputation: 15660

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?

Upvotes: 2

Views: 10016

Answers (2)

berlin
berlin

Reputation: 526

Similar to what the components are writing, previously one would use functions likecomponentDidUpdate & componentDidMount to manipulate components after/before being rendered. Funcitonal components realised we could use one 'hook' for this called useEffect where one can trigger a particular action to occur on the basis of a state change to the component.

Here is a link to the docs for useEffect - https://reactjs.org/docs/hooks-effect.html

Upvotes: 1

shivamragnar
shivamragnar

Reputation: 414

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
 }, [])

}

Upvotes: 4

Related Questions