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.
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.
How do I create a website with a React Front end and a Flask backend?
I have created websites using flask and templates, and I have made pages using react, and now I would like to combine them.
I have tried a few things and the only things that worked required going into react config files and were very complicated. And even then it was complicated to use fetch and I had to run npm run build every time I changed the react file.
This seems to me like something that would be done all of the time yet I can't find any simple resources to do this.
Is there something that I fundamentally don't understand regarding websites and I am going at this the wrong way?
Focusing on a development workflow, as there are countless choices in how to deploy to a production environment.
Run your Flask app with /api as the root url prefix, either manually by prefixing all your route decorators or with the use of a Blueprint.
py/app.py
#app.route('/api')
def index():
return {'message':'hello'}
Add the Flask development server url to your package.json file
js/package.json
{
...,
"proxy": "http://localhost:5000"
}
Fetch your data using a component
js/Flask.js
import React, { Component } from 'react'
export class Flask extends Component {
constructor(props) {
super(props)
this.state = { data: {}, status: null }
}
fetchData() {
let status
fetch('/api')
.then((res) => {
return {
data: res.json(),
status: status
}
})
.then((data) => {
this.setState({ ...data })
}
.catch((err) => {
console.error(err)
})
}
componentDidMount() {
this.fetchData()
}
render() {
const { data, status } = this.state
return (
<div>
<h3>Status: { status }</h3>
<pre>
{ JSON.stringify(data) }
</pre>
</div>
)
}
}
export default Flask
Finally, include the component in your main App
js/App.js
import React from 'react';
import Flask from './Flask'
function App() {
return (
<div className="App">
<Flask />
</div>
);
}
export default App;
Start your Flask server with your preferred method, either flask run or by executing your script directly, then start your JS development server with either yarn or npm start. You should see the response from your api route displayed at http://localhost:8000
As long as you are running your Flask server with debug=True and use npm start (not npm run build), any changes made with either the backend or frontend will be automatically detected and your app reloaded.
I am trying to use react-recaptcha-v3 (https://www.npmjs.com/package/react-recaptcha-v3) and I exactly wrote the example :
import React, { Component } from 'react';
import { ReCaptcha } from 'react-recaptcha-v3'
import { loadReCaptcha } from 'react-recaptcha-v3'
class ExampleComponent extends Component {
verifyCallback = (recaptchaToken) => {
// Here you will get the final recaptchaToken!!!
console.log(recaptchaToken, "<= your recaptcha token")
}
componentDidMount() {
loadReCaptcha('site key (I can't give it here)')
}
render() {
return (
<div>
<ReCaptcha
sitekey="site key (I can't give it here)"
action={console.log('action')}
verifyCallback={this.verifyCallback}
/>
<h2>Google ReCaptcha with React </h2>
<code>
1. Add <strong>your site key</strong> in the ReCaptcha component. <br/>
2. Check <strong>console</strong> to see the token.
</code>
</div>
);
};
};
export default ExampleComponent;
I wrote my domains names like this :
localhost
localhost:3000
And I got a site key and a secret key.
Here is what i get in console :
New answer :)
Firstly, I'm unsure if you said you added localhost & localhost:3000 to allowed domains. If you did you should remove them
We advise to use a separate key for development and production and to not allow localhost on your production site key.
Even if you are using this for a test environment I wouldn't recommend it. Instead use the test site key & secret key. Localhost is enabled for test.
Next, I noticed your comment about using reCaptcha v2. If you are trying to implement reCaptcha the way v3 intends this won't work.
reCaptcha v2
Adds a script to a div that detects a users input checking if they a human.
reCaptcha v3
Adds an invisible div that detects wether it thinks the user is a bot or not. You have to setup a backend for it to work. It creates a score from 0.0 to 1.0. 0.0 meaning it is most likely a bot, 1.0 meaing it is most likely a human. It uses a token and then on your backend gives you a response that looks like this.
{
"success": true|false, // whether this request was a valid reCAPTCHA token for your site
"score": number // the score for this request (0.0 - 1.0)
"action": string // the action name for this request (important to verify)
"challenge_ts": timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
"hostname": string, // the hostname of the site where the reCAPTCHA was solved
"error-codes": [...] // optional
}
https://developers.google.com/recaptcha/docs/faq
Next, I checked the documentation of the package.
You can't use loadReCaptcha in the same component, it must be in a Parent. Also action={console.log('action')} needs to be a string action="action" you configure this string in your google account.
https://developers.google.com/recaptcha/docs/v3#frontend_integration
Next, I won't recommend relying on a package as you make an uanessacry dependency.
I wrote an article here about it https://medium.com/#alexjamesdunlop/unnecessary-packages-b3623219d86.
import React, { Component } from 'react';
class ExampleComponent extends Component {
componentDidMount() {
const script = document.createElement("script")
script.src = "https://www.google.com/recaptcha/api.js?render=_reCAPTCHA_site_key"
script.addEventListener("load", () => {
window.grecaptcha.ready(function() {
window.grecaptcha.execute('_reCAPTCHA_site_key_', {action: 'homepage'}).then(function(token) {
// ...
});
});
})
document.body.appendChild(script)
}
render() {
return (
<div
className="g-recaptcha"
data-sitekey="_Your_Key_"
data-size="invisible"
>
</div>
)
}
}
export default ExampleComponent;
If you do want to continue using the package this is what it should look like.
import React, { Component } from 'react';
import { loadReCaptcha, ReCaptcha } from 'react-recaptcha-v3'
class ExampleComponent extends Component {
verifyCallback = (token) => {
// This is the token you send to your backend
console.log("token: ", token)
}
render() {
return (
<div>
<ReCaptcha
sitekey={your_site_key}
// This must be a string and an example google gives is 'homepage' or 'login'
action="action"
verifyCallback={this.verifyCallback}
/>
</div>
)
}
}
class ParentComponent extends Component {
componentDidMount() {
loadReCaptcha(your_site_key)
}
render() {
return <ExampleComponent />
}
}
export default ParentComponent;
Now if you did want to use v2 instead of v3 I show how to do that in the article
https://medium.com/#alexjamesdunlop/unnecessary-packages-b3623219d86
I recommend moving away from react Components and moving towards hooks, it's common practice to move away from it now, Components isn't supported.
https://reactjs.org/docs/hooks-effect.html
I created complete offline ReactJS web application and I want to run it from android application from Web View using React-Native.
I followed the following procedure to do so:
1. I created a compiled ReactJS web application got the build using the following command:
npm run build
Then I created react-native project and placed the build folder with following architecture
I updated App.js with the following content:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, WebView} from 'react-native';
import {roscon} from "./build/index.html";
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={{height: 300, width: 300,overflow:'hidden' }}>
<WebView
source={{uri: roscon}}
scalesPageToFit={true}
domStorageEnabled={true}
javaScriptEnabled={true}
startInLoadingState={true}
/>
</View>
);
}
}
After running this code I expected it to run my ReactJS Web application, instead I got white screen.
Can you please tell what can be the causing issues and how i can make my ReactJS Web App run on react-native?
Note: I was able to run generated build folder using npm command
serve -s build
But I still can't figure out how to port it to react-native project as WebView
After research and testing, I found a solution.
The main issue i found was the compiled build folder is rendered as static html. And it needed a server to serve pages.
So, I followed this link for getting build project to get it up and running
Then, integrating it with nodejs Android Project Samples to get my build folder running in android as a Webview.
Note: I also tried react-snapshot and react-snap but they didn't gave satisfactory results.
Try to require the html file correctly and pass it in to source prop in this way:
<WebView
source={require('./build/index.html')}
/>
Install
npm install react-native-react-bridge
These are used to render React app in WebView
npm install react-dom react-native-webview
Requirements
react 16.8+
react-native 0.60+
Usage
Fix metro.config.js to use babelTransformer from this library.
module.exports = {
transformer: {
babelTransformerPath:
require.resolve('react-native-react- >.
.bridge/lib/plugin'),
...
},
};
Make entry file for React app. web.js
import React, { useState } from "react";
import {
webViewRender,
emit,
useSubscribe,
} from "react-native-react-bridge/lib/web";
const Root = () => {
const [data, setData] = useState("");
// useSubscribe hook receives message from React Native
useSubscribe((message) => {
if (message.type === "success") {
setData(message.data);
}
});
return (
<div>
<div>{data}</div>
<button
onClick={() => {
// emit sends message to React Native
// type: event name
// data: some data which will be serialized by JSON.stringify
emit({ type: "hello", data: 123 });
}}
/>
</div>
);
};
// This statement is detected by babelTransformer as an entry point
// All dependencies are resolved, compressed and stringified into one file
export default webViewRender(<Root />);
Use the entry file in your React Native app with WebView.
import React from "react";
import WebView from "react-native-webview";
import { useBridge } from "react-native-react-bridge";
import webApp from "./WebApp";
const App = () => {
// useBridge hook create props for WebView and handle communication
// 1st argument is the source code of React app
// 2nd argument is callback to receive message from React
const { ref, source, onMessage, emit } = useBridge(webApp, (message) => {
// emit sends message to React
// type: event name
// data: some data which will be serialized by JSON.stringify
if (message.type === "hello" && message.data === 123) {
emit({ type: "success", data: "succeeded!" });
}
});
return (
<WebView
// ref, source and onMessage must be passed to react-native-webview
ref={ref}
source={source}
onMessage={onMessage}
/>
);
};
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)