top of page
Logo der Online Agentur mdwp

useRef

React Js useRef is a built-in hook in React that allows you to directly access the DOM (Document Object Model) elements or any other elements in your component. useRef returns a mutable reference object which .current property can be initialized to the argument passed (initialValue). Returned object will persist for the full lifetime of the component. This is particularly handy in cases where you want to maintain a value across several re-renderings of a component and don’t want to trigger further re-renderings.

Here's a code snippet of how you can use React's useRef:

```jsx
import React, { useRef } from 'react';

function TextInputWithFocusButton() {
// Initialise the useRef
const inputEl = useRef(null);

const onButtonClick = () => {
// Access the input element directly
// This would print the text into the console
console.log(inputEl.current.value);
};

return (
<>
{/* Attaching the useRef instance to the element */}
<input ref={inputEl} type="text" />

<button onClick={onButtonClick}>Print text</button>
</>
);
}

export default TextInputWithFocusButton;
```

In this example, `useRef(null)` creates a reference, `inputEl`, which then gets attached to the `<input />` element in the returned JSX. The `ref` passed to the `input` element is like a “box” that can hold a DOM node in its `current` property.

When the `Print text` button is clicked, `onButtonClick` is triggered, it accesses `inputEl.current` and logs the value of the input field. This shows that we directly accessed the DOM using useRef.

bottom of page