3

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?

2
  • 1
    You can do that using useEffect function if you are using react hooks or lifecycle methods from the react class. Commented Feb 19, 2021 at 9:25
  • 1
    For this you need a useRef hook reactjs.org/docs/hooks-reference.html#useref Commented Feb 19, 2021 at 9:25

2 Answers 2

5

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

}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.