sanjay singh
sanjay singh

Reputation: 11

Html element set autofocus dynamically in React

I have two sibling component.

one component contains textbox,checkbox,dropdown controls in it.

another component contains Kendo Grid.

whenever user clicks on grid row i want to set focus on one of the element in above component which include textbox.

Approach used:

1.I don't want to use ref as i have multiple controls in one component.

2.I have dynamically added autofocus attribute to input element.

Upvotes: 1

Views: 1597

Answers (1)

WebDeg Brian
WebDeg Brian

Reputation: 832

Disclaimer: I am not sure if these solutions are best practices in React

There are 2 approaches for this, both using refs, but with smarter implementations:

  • Create a wrapper around the inputs and assign refs to it. Whenever you want to focus on an input, simply use wrapperRef.querySelector('[name=yourInput]). Working example: https://codesandbox.io/s/195kkrpvq
  • Create an object which stores the name of the fields as keys and their refs as values. Simply use this.yourRefsObject[yourInputName].focus() to focus on an input. Working example: https://codesandbox.io/s/61jl7q9v43

Again, I am not certain whether these implementations are best practices, but they should do the job for now

Upvotes: 1

Related Questions