Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic refs using ref callback method

Tags:

react-native

How do you suppose setting a dynamic ref now? Im getting an error cannot set property of 'test' undefined, if I use

<View ref={(ref) => this.someRef['test'] = ref;}/>
like image 256
Jan Avatar asked Mar 10 '17 16:03

Jan


People also ask

What is ref callback?

Callback Refs The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere. The example below implements a common pattern: using the ref callback to store a reference to a DOM node in an instance property. class CustomTextInput extends React.

How do you make refs dynamically React?

To add refs to React components, we first create a ref, and then we add the ref to the component using the ref attribute. There are two ways to create refs in React the first is by using React. createRef() method or the useRef() hook.

Which is preferred option with in callback refs and findDOMNode ()?

Q-5: Which is preferred option with in callback refs and findDOMNode()? It is preferred to use callback refs over findDOMNode() API. Because findDOMNode() prevents certain improvements in React in the future.

Why ref is not recommended in React?

We should not use ref attribute on function components because they do not have instances. React will assign the current property with Dom element when component mount and assign null to it when component unmount. ref updates happen before componentDidMount or componentDidUpdate methods.


1 Answers

You have to set this.someRef to an array or object before assigning a property to it.

this.someRef = [];
or
this.someRef = {};
like image 123
vinayr Avatar answered Sep 17 '22 08:09

vinayr