I started programming in React Native, and I got used to use the syntax:
async myFunction(){
...
return await otherFunction();
}
But I don't know how to make it compatible with React JS and React Native in a shared package. How can I accomplish this so that it works in both platforms?
Thanks!
If you building using create-react-app it's been available since v0.2.3
https://github.com/facebookincubator/create-react-app/releases/tag/v0.2.3
It can be used inside a Component like this
class App extends Component {
constructor(props) {
super(props);
this.state = { message: '' };
}
async componentDidMount() {
this.setState({ message: 'loading...' });
let d = await getData('/posts/1');
this.setState({ message: d });
}
render() {
let { message } = this.state;
return (
<div className="App">
<p className="App-intro">
{ message }
</p>
</div>
);
}
}
See:
https://github.com/facebookincubator/create-react-app/issues/1024
React Native ships with Babel and some Babel presets, whereas React on the web is just React related code.
If you want to use async/await on the web today you'll need Babel and the correct transforms: https://babeljs.io/docs/plugins/transform-async-to-generator/
or the stage-1 presets, which is fairly common in React apps today. http://babeljs.io/docs/plugins/preset-stage-1/
Alternatively you can use Typescript.
Since version 2.1 it is possible to use async/await and directly transpile to ES5 (in other words have it run on ~all browsers)
Related
I wanna use Google Maps API in React.
I read this article and found out that some packages were released recently.
But I don't know even if I look at the example.
How can I use Google Maps in React?
I want to take a marker, change the marker icon.
Please help me...
Definitely understand that there are packages that help you load Google Map and the Javascript API, e.g.
https://www.npmjs.com/package/google-map-react
https://www.npmjs.com/package/#react-google-maps/api
I used google-map-react before, but now I need a more flexible way to load the Google Maps JavaScript API script.
For those like me who got here by searching for how to use #googlemaps/js-api-loader in React, here is some code sample.
install the npm package:
npm i #googlemaps/js-api-loader
code sample:
import React, { Component } from 'react';
import { Loader } from '#googlemaps/js-api-loader';
const loader = new Loader({
apiKey: "YOUR_API_KEY"
version: "weekly",
libraries: ["places"]
});
export default class DemoComponent extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
let self = this;
const defaultMapOptions = {
center: {
lat: 40.762312,
lng: -73.979345
},
zoom: 11
};
loader.load().then((google) => {
const map = new google.maps.Map(
self.googleMapDiv,
defaultMapOptions);
/*
store them in the state so you can use it later
E.g. call a function on the map object:
this.state.map.panTo(...)
E.g. create a new marker:
new this.state.google.maps.Marker(...)
*/
this.setState({
google: google,
map: map
});
});
}
render() {
return (
<div
ref={(ref) => { this.googleMapDiv = ref }}
style={{ height: '100vh', width: '100%' }}>
</div>
)
}
}
Have you checked out this package and its documentation:
https://www.npmjs.com/package/#react-google-maps/api
I've used it to create a google map inside a React functional component.
There are other react google map packages out there as well.
Before adding webpack this worked, after adding it it stop works.
export class Main extends Component {
constructor(props) {
super(props);
this.state = {
currentPage: states.allProducts
};
this.handleClick = this.handleClick.bind(this);
}
async componentDidMount() {
let currentPage = this.state.currentPage;
}
handleClick() {
alert('a');
}
render() {
return (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
}
It is highly recommended to use create-react-app.
It will set up and installing all babel plugins and presets by its own, so you don't face such an issue.
As mentioned here How To Use Async Await in React
Now, create-react-app supports async/await out of the box. But if you have a webpack boilerplate you may hit an error (more in a minute).
it is because lack of some babel plugins, you can install them, and hopefully, everything will work fine again
How can i declarate componentDidMount without creating class extends react component? For example render() declarates with react-dom package, maybe is exist another package for componentDidMount?
class App extends Component {
constructor(){
// do something
}
componentDidMount(){
// js code must run after page loaded
}
render(){
return(
<div className="app">
</div>
);
}
}
export {App};
The same thing with component constructor()
const App = () => {
// constructor and componentDidMount does not work here
// js code must run after page loaded
return (
<div className="app">
</div>
);
};
export {App};
First of all, what you want to achieve is fully Meteor independent. It's a pure React problem that could exist with any backend. What you want to achieve can be done using the useEffect() hook for which you'll find the documentation right here:
https://reactjs.org/docs/hooks-reference.html#useeffect
Here is a great article explaining how to replace lifecycle methods with hooks:
https://dev.to/trentyang/replace-lifecycle-with-hooks-in-react-3d4n
In your case, for componentDidMount you'll have to do the following:
useEffect(() => {
// js code must run after page loaded
}, []);
In the final array you have to put dependency that will retrigger the hook if you need. To imitate a simple componentDidMount an empty array is generally the solution.
I'm trying to use this library https://github.com/country-regions/react-country-region-selector for my react native application.
The example code is as follows:
import React from "react";
import { View, Text } from 'react-native';
// note that you can also export the source data via CountryRegionData. It's in a deliberately concise format to
// keep file size down
import {
CountryDropdown,
RegionDropdown,
CountryRegionData
} from "react-country-region-selector";
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { country: "", region: "" };
}
selectCountry(val) {
this.setState({ country: val });
}
selectRegion(val) {
this.setState({ region: val });
}
render() {
const { country, region } = this.state;
return (
<View>
<CountryDropdown
value={country}
onChange={val => this.selectCountry(val)}
/>
<RegionDropdown
country={country}
value={region}
onChange={val => this.selectRegion(val)}
/>
</View>
);
}
}
export default Example;
I changed the divs in the render method into View, which has left me with the current error: Invariant Violation: View config not found for name option.
I'm not sure if this is because the library is intended for React as opposed to React-Native or if there is something else going on that I'm unaware of.
This won't work because this library renders HTML, which is not available in react-native. You can confirm this by going to node_modules/react-country-region-selector/src to see the source code.
However, the Picker component in react-native has a very similar API, so you could easily remake this to be compatible. Note that you should not edit files in your node_modules as they will be corrected any time you run yarn / npm. Instead, you should create your own local version of this module.
It's really just a matter of replacing select with Picker and option with Picker.Item and changing the onChange handlers to work with the Picker instead of expecting a DOM event.
You can learn more about the Picker API here
I'm new to react. And I'm expecting to build a mobile Application from Web-App using Cordova plug-in.
So in this case I want to get the App location. I'm trying this with react-native Geolocation.
I followed the tutorial from facebook at here. But when I tried it, It does not show me the position. Instead value of the position change from unknown to {}.
There might be few errors I'm doing here.
I'm using a proxy
Testing this in browser not in Android or any other native device.
Facebook Link says it is react-native but my project was created by create-react-app which I think not React-native
If any of these is not the cause for this error, Please help.
My code,
import React,{Component} from 'react';
class GeoLocation extends React.Component {
state = { initialPosition: 'unknown',
lastPosition: 'unknown', };
watchID: ?number = null;
componentDidMount() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition( (position) => {
var initialPosition = JSON.stringify(position);
this.setState({initialPosition});
},
(error) => alert(JSON.stringify(error)), {
enableHighAccuracy: true, timeout: 20000, maximumAge: 1000
} );
this.watchID = navigator.geolocation.watchPosition((position) => {
var lastPosition = JSON.stringify(position);
this.setState({lastPosition});
});
}
}
componentWillUnmount() {
navigator.geolocation.clearWatch(this.watchID);
}
render() {
return (
<div className="main">
<h1> Initial position: {this.state.initialPosition} </h1>
<h1> Current position: {this.state.lastPosition} </h1>
</div>
);
}
}
export default GeoLocation;
At HyperTrack we have built a location service and included some React libraries and sample apps for React and Cordova found on our Github. Likely this would solve the issues you are having with grabbing location, or at least get you on the right track.