Khurshid Ansari
Khurshid Ansari

Reputation: 5095

How to use ref in another component in react native?

I have using react native mpaboxgl in my application.

import MapboxGL from "@mapbox/react-native-mapbox-gl";


<MapboxGL.MapView
  logoEnabled={false}
  attributionEnabled={false}
  ref={(e) => { this.oMap = e }}
  zoomLevel={6}
  centerCoordinate={[54.0, 24.0]}> 
<MapboxGL.MapView> 

How to use oMap in another component? So I can do something like layer on/off from other component/page.

Upvotes: 2

Views: 8723

Answers (2)

Shashin Bhayani
Shashin Bhayani

Reputation: 1576

UPDATE :

use a global variable that will work.

ref={ref=>{
   global.input=ref;
   }}

now you can use global.input.focus() anywhere in the app after this screen.


here is an example to achieve this: https://snack.expo.io/ryJk3hFKN

you can create one function which returns ref of that component.
and pass that function as props in other components

import * as React from 'react';
import { Text, View, StyleSheet, TextInput, TouchableOpacity } from 'react-native';

export default class App extends React.Component {
  getInputRef = () => this.input;

  render() {
    return (
      <View style={styles.container}>
        <TextInput
          ref={ref => {
            this.input = ref;
          }}
          placeholder="Hi there"
        />
        <SecondComp getInputRef={this.getInputRef} />
      </View>
    );
  }
}

class SecondComp extends React.Component {
  render() {
    return (
      <TouchableOpacity
        onPress={() => {
          this.props.getInputRef().focus();
        }}>
        <Text>click to Focus TextInput from the other component</Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'space-around',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

Upvotes: 5

avani kothari
avani kothari

Reputation: 739

Try passing it as a prop to the component you want to use the refs in. For eg.

<SecondComponent refOfFirstComponent = this.refs.oMap/>

and in SecondComponent use it anywhere like this:

this.props.refOfFirstComponent.doSomething();

Upvotes: 0

Related Questions