1

I have something like this:

<App>
    <CommentForm/>
    <CommentList/>
</App>

<App> has shared states for <CommentForm/> and <CommentList/>.

<CommentForm/> has form and after comment is submitted it appears in <CommentList>.

It all works fine expect that I cannot find good way of triggering focus() event on textarea in <CommentForm>.

I know that I can do it by creating ref, but as I known it is not really a good practice.

Is there a way to trigger focus event using state in React?

Btw, I am not interested in autoFocus.

5
  • 2
    In the When to Use Refs section of the react docs, the 1st line starts with "Managing focus". Don't use refs to get the data from forms, or change styles, but focus is fine. Commented Jul 14, 2018 at 18:26
  • @OriDrori is it really the only best practice-like option? Commented Jul 14, 2018 at 18:27
  • 1
    a ref is not a bad practice. It is a very powerful tool when used correctly. But that being said when something is created (ref in this instance) it gets used in ways that is not intended (like applying styles or getting data out of a form). However focus is a great example of when to use a ref. Commented Jul 14, 2018 at 18:30
  • 1
    It's actually the only react way to set focus. Commented Jul 14, 2018 at 18:31
  • there is onFocus Synthetic event in react. here is link to react [docs]: [reactjs.org/docs/events.html#focus-events] Commented Jul 15, 2018 at 0:35

1 Answer 1

2

If you have an id set to your input component you can do the following:

document.getElementById('yourInputId').focus();

Even though you can use this code I recommend you to use refs instead due to reusability.

You can check a few more info on this post: https://www.javascriptstuff.com/use-refs-not-ids/

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

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.