top of page
Logo der Online Agentur mdwp

Refs

Refs, short for "References", in React JS are a useful feature that allow us to interact with and access properties of components directly.

In most cases, the use of refs should be avoided because they tend to make code harder to understand. But there's situations where refs can turn quite handy, for example, managing focus, text selection, or media playback. Another common use case is triggering imperative animations. They can also help integrate with third-party DOM libraries.

Here's an example of using refs in React:

```jsx
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
```

In this case, `myRef` is the ref and it is assigned to an empty `<div>`. Anywhere in the component, `this.myRef.current` would contain the DOM node of that `<div>`.

Here's a focus example:

```jsx
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
focusTextInput = () => {
// Directly using the raw DOM API
if (this.textInput.current) {
this.textInput.current.focus();
}
};
render() {
return (
<div>
<input
type="text"
ref={this.textInput} />

<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
```
In this example, `input` is given a ref by passing the property `ref={this.textInput}` and the `focusTextInput` method can use it to set the focus when the button is clicked. Remember that this way of directly interacting with the DOM should be used sparingly and should be as a last resort, as it can make your components more difficult to handle and test. A more idiomatic React solution would be making the text input a controlled component and then setting the focus with a state change.

bottom of page