How can I get the value of a variable sent in a WebView in the HTML page? - react-native

I am developing an App that needs to send variables to an html page that will be displayed in a WebView. Here is a basic example of the React Native Application code.
export default class App extends Component {
render()
{
let variableCadena="React Native";
return(
<Container>
<WebView
style={{flex: 1}}
originWhitelist={['*']}
source={{uri:'file:///android_asset/PaginaEjemplo.html'}}
style={{ marginTop: 20 }}
javaScriptEnabled={true}
domStorageEnabled={true}
allowFileAccess={true}
allowUniversalAccessFromFileURLs={true}
injectedJavaScript={variableCadena}
>
</WebView>
</Container>
);
}
};
The HTML can be as simple as the following one.
<html>
<head>
<title>Ejemplo de inyeccion desde React Native</title>
<script type="text/javascript">
var variable = variableCadena;
</script>
</head>
<body>
<script type="text/javascript">
document.body.innerHTML = "<h1>La variable es:"
+variable+ "</h1>"
</script>
</body>
</html>
The result that is expected is that the web page shows in the h1 tags the React Native text that was defined in the application. Thank you all for your suggestions.

First of all, I hope you are using https://github.com/react-native-community/react-native-webview instead of the from react-native because it's now being deprecated.
You can use the injectJavascript(...) method. Something like this...
import React, { Component } from 'react';
import { View } from 'react-native';
import { WebView } from 'react-native-webview';
export default class App extends Component {
render() {
const run = `
document.body.style.backgroundColor = 'blue';
true;
`;
setTimeout(() => {
this.webref.injectJavaScript(run);
}, 3000);
return (
<View style={{ flex: 1 }}>
<WebView
ref={r => (this.webref = r)}
source={{
uri: 'https://stackoverflow.com/questions/57065527',
}}
/>
</View>
);
}
}
that will give you something like this:
Now work around that! Check the snack: https://snack.expo.io/#abranhe/stackoverflow-57065527
UPDATE the author requested a demo using a variable
App.js
import React, { Component } from 'react';
import { View } from 'react-native';
import { WebView } from 'react-native-webview';
export default class App extends Component {
injectjs() {
let name = 'Abraham';
setTimeout(() => {});
return `document.getElementById('inject').innerHTML = '<h1>The name is <b>${name}</b></h1>'`;
}
render() {
return (
<View style={{ flex: 1 }}>
<WebView
ref={(r) => (this.webref = r)}
injectedJavaScript={this.injectjs()}
source={require('./demo.html')}
/>
</View>
);
}
}
demo.html
<html>
<head>
<title>Ejemplo de inyeccion desde React Native</title>
<style>
body {
background-color: aquamarine;
display: -webkit-flex;
-webkit-justify-content: center;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
</style>
</head>
<body>
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg?v=a010291124bf" />
<div id="inject">
</body>
</html>
Result

Related

How can I change the color of the component that I created after calling?

For the below logout component I want to change its TintColor and text color , what should I code?
I tried adding style here but it doesn't work.
<MenuItems listingname="Logout"
onPress={() => {
this.RBSheet.close();
this.props.notifyCountrUpdtHndlr(0)
AuthHelpers.logout(this.props.navigation,true);
}}
imagesource ={IMAGE.LOGOUT_ICO}/>
you can go inside MenuItems component and change the style there
(click on MenuItems component name and press F12 key)
just find Image and Text Component and add your styles
(to find Image and Text component inside MenuItems search listingname and imagesource)
<Image style={yourNewStyle}/>
<Text style={yourNewStyle}> </Text>
The very basic method you can use Inline CSS
<div style={{ backgroundColor: 'red' }}>
This component has a red background
</div>
And Another Method is Using CSS class selector
.red-background {
background-color: red;
}
// component
<div className="red-background">
This component has a red background
</div>
Also you can change the color of the component dynamically like
import React, { Component } from 'react';
import { View, Text } from 'react-native';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
backgroundColor: '#F5FCFF'
};
}
changeColor = () => {
this.setState({
backgroundColor: '#123456'
});
}
render() {
return (
<View style={{backgroundColor: this.state.backgroundColor, height:100, width: 100}}>
<Text onPress={this.changeColor}>Click Me!</Text>
</View>
);
}
}
export default MyComponent;

react-responsive Invalid-hook-call

I 'm trying to use react-responsive in a monorepos with styled-component and react-native-web.
I've a workspace like my ui lib and i define my component like that:
import styled from 'styled-components/native';
import { theme } from '#components/theme';
import MediaQuery from 'react-responsive';
interface CardProps {
children: React.ReactNode;
tag: string;
}
const Card = (props: CardProps) => {
console.log("Card -> props", props)
return (
<Container>
<MediaQuery minDeviceWidth={1000}>
<Tag>'blablabla</Tag>
</MediaQuery>
<TagContainer>
<Tag>{props.tag}</Tag>
</TagContainer>
<MainContent>{props.children}</MainContent>
</Container>
);
}
I define the style like that:
const Container = styled.View`
display: flex;
flexDirection: column;
minWidth: ${theme.width.minCard};
maxWidth: ${theme.width.maxCard};
height: ${theme.height.card};
boxShadow: 0 0 10px ${theme.colors.primaryGrey};
border: 1px solid ${theme.colors.primaryYellow};
borderRadius: ${theme.borderRadius.rectangular};
marginBottom: ${theme.margins.medium};
`;
const TagContainer = styled.View`
display: flex;
flexDirection: row-reverse;
`;
I'm trying to use this component in my react-native app located in another workspace like this:
return (
<View>
<Specialist
key={psychologist.uuid}
img={psychologist.avatar.url}
name={psychologist.fullname}
job={psychologist.job_name}
description={psychologist.description}
/>
</View>
);
Each time, I find myself blocked by this error:
however my component is indeed a functional component...
Any idea ?
the package you are using is only for react.js.
For React Native you can use
React Native Responsive Screen
example given in react-native-responsive-screen
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
class Login extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.textWrapper}>
<Text style={styles.myText}>Login</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: { flex: 1 },
textWrapper: {
height: hp('70%'), // 70% of height device screen
width: wp('80%') // 80% of width device screen
},
myText: {
fontSize: hp('5%') // End result looks like the provided UI mockup
}
});
export default Login;

How to create graph using canvas in react-native and render dynamical coordinates of line?

I have tried doing it with react-native-webview, but i was unable to get my coordinates to the center. As well i was not unable fix the height and width. Below is my code, any suggestions would be appreciated. I have tried doing it with react-native-webview, but i was unable to get my coordinates to the center. As well i was not unable fix the height and width. Below is my code, any suggestions would be appreciated.
import React, { useEffect, useRef } from 'react'
import { StyleSheet, View, Text, Dimensions } from 'react-native'
import { WebView } from 'react-native-webview';
const WebViewGraph = () => {
const theCanvas = useRef(null);
useEffect(() => {
let xWidth = Dimensions.get('window').width, yHeight = Dimensions.get('window').height
console.log(xWidth, yHeight);
// const jscode = `document.getElementById("chart").getContext("2d").fillRect(200, 80, 100, 50)
// document.getElementById("chart").getContext("2d").strokeRect(80, 20, 100, 50)`;
const jscode = `document.getElementById("chart").getContext("2d").beginPath()
document.getElementById("chart").getContext("2d").lineWidth = "5"
document.getElementById("chart").getContext("2d").strokeStyle = "green"
document.getElementById("chart").getContext("2d").moveTo(${xWidth/2},0)
document.getElementById("chart").getContext("2d").lineTo(${xWidth/2},${yHeight})
document.getElementById("chart").getContext("2d").stroke()
document.getElementById("chart").getContext("2d").moveTo(0,${yHeight/2})
document.getElementById("chart").getContext("2d").lineTo(${xWidth},${yHeight/2})
document.getElementById("chart").getContext("2d").stroke()
`;
canvasRef.injectJavaScript(jscode);
}, [])
let init = `
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
</head>
<body>
<div>
<canvas id="chart"></canvas>
</div>
</body>
</html>`
const onMessage = (data) => {
console.log(data)
}
return (
<View style={styles.full}>
<WebView
ref={theCanvas => (canvasRef = theCanvas)}
originWhitelist={['*']}
style={{backgroundColor: 'grey', marginTop: 30, height: 400, width: 800}}
source={{ html: init, baseUrl: 'web/' }}
javaScriptEnabled
domStorageEnabled
scalesPageToFit
scrollEnabled={false}
automaticallyAdjustContentInsets
onMessage={onMessage}
/>
{/* <Text>Heyy</Text> */}
</View>
)
}
const styles = StyleSheet.create({
full: {
flex: 1,
backgroundColor: '#c3c3c3'
}
});
export default WebViewGraph;

react native doesn't show video in my native application, what's the solution?

react native da emulator comes blank white page, does not show video, how can I see my video?
react native da emulator comes blank white page, does not show video, how can I see my video?
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
export default class HelloWorldApp extends Component {
render() {
return (
<View style={styles.videoContainer}>
<Video
source={{ uri: 'http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4' }}
ref={(ref) => {
this._player = ref
}}
style={styles.video} />
</View>
);
}
}
const styles = StyleSheet.create({
videoContainer: {
flex: 1,
},
video: {
position: 'absolute',
top: 0,
right: 0,
left: 0,
}
})
export default styles;
first you export default two things which is wrong. run the below code its is working
import React, { Component } from 'react';
import Video from 'react-native-video';
import { Text, View, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
videoContainer: {
flex: 1,
},
video: {
flex: 1,
}
});
export default class HelloWorldApp extends Component {
render() {
return (
<View style={styles.videoContainer}>
<Video
source={{ uri: 'http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4' }}
ref={(ref) => {
this._player = ref
}}
style={styles.video} />
</View>
);
}
}

Image Slider implemented using Carousel is not working

I am working on an App which can display a simple Image Slider using Carousel.
I have used the Carousel from "react-native-banner-carousel" library.
Code:
ImageSlider.js
import React from 'react';
import Carousel from 'react-native-banner-carousel';
import { StyleSheet, Image, View, Dimensions } from 'react-native';
const BannerWidth = Dimensions.get('window').width;
const BannerHeight = 260;
const images = [
"https://images-na.ssl-images-amazon.com/images/I/61McsadO1OL.jpg",
"https://images-na.ssl-images-amazon.com/images/I/51vlGuX7%2BFL.jpg",
"https://images-na.ssl-images-amazon.com/images/I/717DWgRftmL._SX522_.jpg"
];
export default class ImageSlider extends React.Component {
renderPage(image, index) {
return (
<View key={index}>
<Image style={{ width: 500, height: BannerHeight }} source={{ uri: image }} />
</View>
);
}
render() {
return (
<View style={styles.container}>
<Carousel
autoplay
autoplayTimeout={5000}
loop
index={0}
pageSize={BannerWidth}
>
{images.map((image, index) => this.renderPage(image, index))}
</Carousel>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
justifyContent: 'center'
},
});
App.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import Header from './components/Header';
import ImageSlider from './components/ImageSlider';
class App extends Component {
render () {
return (
<View>
<Header headerText = "SAMPLE APP" />
<ImageSlider />
</View>
);
}
}
export default App;
I am importing ImageSlider inside the App.js
I am trying the method mentioned in this link: https://github.com/f111fei/react-native-banner-carousel
But the output I am getting is somewhat like this:
Where am I going wrong here?
class App extends Component {
render () {
return (
<View style={{flex:1}}>
<Header headerText = "SAMPLE APP" />
<ImageSlider />
</View>
);
}
}
Notice this in the above code
<View style={{flex:1}}>
Hope this will help.!