0

I am new to react-native and am trying to build a Map component that relies on a GPS component. (I am actually not even sure if 'component' is the correct word)

I want to render the map using a UI, but I also need the GPS to get the location information.

Now, how can I create a GPS class including all the GPS logic, calling only a single function to update the location on the page page? Or more specifically, how can I separate the GPS code into a new file without having to call a <GPSComponent /> within the render method of the map-component?

To be more specific with the code example, I put it on CodePen here https://codepen.io/yeni/pen/WOrjJx

DaveTheAl
  • 1,995
  • 4
  • 35
  • 65

2 Answers2

2

Just put your GPS class in a separate file. The class should not extend Component.

Then import your GPS class in your UI Component (e.g. import gps from './gps') and use it :)

Fabian
  • 531
  • 4
  • 11
  • thanks for the answer! how do I have to manage the clearWatch flag then however? in the end, the gps cannot rely on componentWillUnmount anymore – DaveTheAl Jun 09 '17 at 10:00
  • hm.. most simple way I'd try: put the clearWatch in a cleanup() method or sth. of the gps class und call that method in the componentWillUnmount of the UI Components that uses the gps class. (Disadvantage: you have to manually make sure, that the cleanup is called in every UI component that uses the gps class) basically: - for your componentDidMount: think of it as the constructor (or sth. like an initialize method) in your new class - for your componentWillUnmount: think of it as the destructor (or sth. like an cleanup method, since destructors don't exist in es6) in your new class – Fabian Jun 09 '17 at 10:12
  • Thanks a lot! So I understand there is no 'natural way' to do it and will try to implement it the way you proposed! :) – DaveTheAl Jun 09 '17 at 13:15
1

another possible way is to return null inside render method

export default class GPSComponent extends React.Component{
    constructor(props){
        super(props);
        // Do some stuff
    }

    someFunctions() { ... }

    render(){
        return null;
    }
}
Sadegh Teimori
  • 1,348
  • 12
  • 12