Dor Ben zvi
Dor Ben zvi

Reputation: 68

Create ref to a component before then component renderd

I'm using react-native-google-places-autocomplete for google places auto-complete. I'm creating a new page to edit the address and I want to use the setAddressText function to insert the last current address before the editing.

I tried to create a ref and store it with redux of the google autocomplete component but since this search bar rendered only when clicking on the edit button the reference hasn't created and I cant use the setAddressText on the ref.

Does anyone have a solution for that?

Upvotes: 0

Views: 117

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42218

You use either useRef or createRef to create the ref object. Before calling any methods on it, you must make sure that myRef.current has been set. The easiest way (if your environment is up-to-date enough to support it) is with the optional chaining operator ?.

myRef.current?.setAddressText(someText);

However I would advise against storing a ref in redux. As a best practice, it is advised that everything in your redux state should be serializable — a ref is not.

Upvotes: 1

Related Questions