1

I have a React class:

export default class FormField extends Component {
  state = {};

  labelRef = React.createRef();
  childRef = React.createRef();
  fieldControlRef = React.createRef();
  ...
}

I don't like that I have three lines assigning the same value to separate properties. Is there a way to it in one line that would work inside a class?

  • If the sole purpose of having Refs was to assign `className` dynamically, you certainly need to get rid of them, there's, actually, very limited scope of scenarios where Refs considered the best choice. Modifying DOM directly is, in general, is not common in React, you should consider using conventional React tools (i.e. state variables) to solve such problems. Look through [my answer](https://stackoverflow.com/a/60655656/11299053) for details. – Yevhen Horbunkov Mar 12 '20 at 14:07

1 Answers1

1

You have to make sure you need the Refs themselves, in the first place.

Other than that, you don't need Refs to assign class names whatsoever, simply have desired className within your component's state, like:

state = {
   className: 'someClassName'
}

Then just apply that upon render:

...
render(){
   <div className={this.state.className}>...
}
...

That will allow you to modify className within your state dynamically (e.g. in response to some user interactions) and re-render corresponding elements accordingly.

Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42