Add WebView via onClick in Expo React-Native - javascript

I need a function that creates new screens with a webview in it.
The main screen of my expo app contains a button "add new Page" which links to a page with a form to add domain, Username, Password.
if this is done, I want a list of pages in my main screen with all pages. for example if I click on "myWebsite1" with the generated link http://user:password#myWebsite1.com this page should be shown in a webview. same for website2, 3 and so on.
Anyone an idea how to do this?
EDIT: I add some code I have right now. For each Task I create, the Domain, User and Password for the webview file should change and be saved at this specific task. (and also open onclick). I turn in a circle
this is my app.js which expo opens first, it contains a Flatlist:
import React, { Component } from "react";
import { AppRegistry, StyleSheet, Text, View, FlatList, AsyncStorage, Button, TextInput, Keyboard, Platform, TouchableWithoutFeedback } from "react-native";
const isAndroid = Platform.OS == "android";
const viewPadding = 10;
const things = {things}
export default class NodeList extends Component {
state = {
tasks: [ ],
text: ""
};
changeTextHandler = text => {
this.setState({ text: text });
};
addTask = () => {
let notEmpty = this.state.text.trim().length > 0;
if (notEmpty) {
this.setState(
prevState => {
let { tasks, text } = prevState;
return {
tasks: tasks.concat({ key: tasks.length, text: text }),
text: ""
};
},
() => Tasks.save(this.state.tasks)
);
}
};
deleteTask = i => {
this.setState(
prevState => {
let tasks = prevState.tasks.slice();
tasks.splice(i, 1);
return { tasks: tasks };
},
() => Tasks.save(this.state.tasks)
);
};
componentDidMount() {
Keyboard.addListener(
isAndroid ? "keyboardDidShow" : "keyboardWillShow",
e => this.setState({ viewMargin: e.endCoordinates.height + viewPadding })
);
Keyboard.addListener(
isAndroid ? "keyboardDidHide" : "keyboardWillHide",
() => this.setState({ viewMargin: viewPadding })
);
Tasks.all(tasks => this.setState({ tasks: tasks || [] }));
}
render() {
return (
<View
style={[styles.container, { paddingBottom: this.state.viewMargin }]}
>
<Text style={styles.appTitle}>Nodes</Text>
<FlatList
style={styles.list}
data={this.state.tasks}
renderItem={({ item, index }) =>
<View>
<View style={styles.listItemCont}>
<TouchableWithoutFeedback onPress={() => Linking.openURL('')}>
<Text style={styles.listItem}>
{item.text}
</Text>
</TouchableWithoutFeedback>
<Button color= "#00BC8C" title="✖" onPress={() => this.deleteTask(index)} />
</View>
<View style={styles.hr} />
</View>}
/>
<TextInput
style={styles.textInput}
onChangeText={this.changeTextHandler}
onSubmitEditing={this.addTask}
value={this.state.text}
placeholder="+ add Node"
returnKeyType="done"
returnKeyLabel="done"
/>
</View>
);
}
}
let Tasks = {
convertToArrayOfObject(tasks, callback) {
return callback(
tasks ? tasks.split("||").map((task, i) => ({ key: i, text: task })) : []
);
},
convertToStringWithSeparators(tasks) {
return tasks.map(task => task.text).join("||");
},
all(callback) {
return AsyncStorage.getItem("TASKS", (err, tasks) =>
this.convertToArrayOfObject(tasks, callback)
);
},
save(tasks) {
AsyncStorage.setItem("TASKS", this.convertToStringWithSeparators(tasks));
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#252525",
padding: viewPadding,
paddingTop: 24
},
list: {
width: "100%"
},
listItem: {
paddingTop: 4,
paddingBottom: 2,
fontSize: 18,
color:"#ffff"
},
hr: {
height: 1,
backgroundColor: "gray"
},
listItemCont: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingTop: 10,
},
textInput: {
height: 40,
paddingRight: 10,
paddingLeft: 10,
borderColor: "gray",
borderWidth: isAndroid ? 0 : 1,
width: "100%",
color:"#ffff"
},
appTitle: {
alignItems:"center",
justifyContent: "center",
paddingBottom: 45,
marginTop: 50,
fontSize: 25,
color:"#ffff"
}
});
AppRegistry.registerComponent("NodeList", () => NOdeList);
and here is my second screen, which contains the component for the WebView:
import React, { Component, useState } from "react";
import { BackHandler } from 'react-native';
import { WebView } from 'react-native-webview';
var $ = require( "jquery" );
export default class nodeView extends Component {
constructor(props) {
super(props);
this.WEBVIEW_REF = React.createRef();
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}
handleBackButton = ()=>{
this.WEBVIEW_REF.current.goBack();
return true;
}
onNavigationStateChange(navState) {
this.setState({
canGoBack: navState.canGoBack
});
}
render(){
return (
<WebView
source={{ uri: `https://${user}:${password}#${domain}` }}
ref={this.WEBVIEW_REF}
style={{ marginTop: 20 }}
onNavigationStateChange={this.onNavigationStateChange.bind(this)}
/>
)
}
}

Create WebView. Create State Which Controls WebView. Add Listener To Button

Related

How to handle volumes of multiple track in react-native sound, i want to play 2 sound together and if i want to decrease sound of one

Here is my code screen code
import React, {Component} from 'react';
import {StyleSheet, Text, TouchableOpacity, View, ScrollView, Alert} from 'react-native';
import Sound from 'react-native-sound';
import BgSoundPlayer from '../../../../Components/BgSoundPlayer/BgSoundPlayer';
const audioTests = [
{
title: 'mp3 remote download',
url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
},
{
title: "mp3 remote - file doesn't exist",
url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-9.mp3',
},
];
const Button = ({title, onPress}) => (
<TouchableOpacity onPress={onPress}>
<Text style={styles.button}>{title}</Text>
</TouchableOpacity>
);
const Header = ({children, style}) => <Text style={[styles.header, style]}>{children}</Text>;
const Feature = ({
title,
onPress,
buttonLabel = 'PLAY',
status,
volumeIncrease,
volumeDecrease,
}) => (
<View style={styles.feature}>
<Header style={{flex: 1}}>{title}</Header>
{status ? <Text style={{padding: 5}}>{resultIcons[status] || ''}</Text> : null}
<Button title={buttonLabel} onPress={onPress} />
<Button title="Volume Increase" onPress={volumeIncrease} />
<Button title="volume Decrease" onPress={volumeDecrease} />
</View>
);
const resultIcons = {
'': '',
pending: '?',
playing: '\u25B6',
win: '\u2713',
fail: '\u274C',
};
function setTestState(testInfo, component, status) {
component.setState({tests: {...component.state.tests, [testInfo.title]: status}});
}
/**
* Generic play function for majority of tests
*/
function playSound(testInfo, component) {
setTestState(testInfo, component, 'pending');
BgSoundPlayer.setSound(testInfo);
}
class MainView extends Component {
constructor(props) {
super(props);
Sound.setCategory('Playback', true); // true = mixWithOthers
// Special case for stopping
this.stopSoundLooped = () => {
if (!this.state.loopingSound) {
return;
}
this.state.loopingSound.stop().release();
this.setState({
loopingSound: null,
tests: {...this.state.tests, ['mp3 in bundle (looped)']: 'win'},
});
};
this.state = {
loopingSound: undefined,
tests: {},
};
}
render() {
return (
<View style={styles.container}>
<ScrollView style={styles.container} contentContainerStyle={styles.scrollContainer}>
{audioTests.map(testInfo => {
return (
<Feature
status={this.state.tests[testInfo.title]}
key={testInfo.title}
title={testInfo.title}
onPress={() => {
playSound(testInfo, this);
}}
volumeIncrease={() => {
BgSoundPlayer.increaseVolume();
}}
volumeDecrease={() => {
BgSoundPlayer.decreaseVolume();
}}
/>
);
})}
<Feature
title="mp3 in bundle (looped)"
buttonLabel={'STOP'}
onPress={() => {
BgSoundPlayer.pouse();
}}
/>
</ScrollView>
</View>
);
}
}
export default MainView;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'gray',
},
scrollContainer: {},
title: {
fontSize: 20,
fontWeight: 'bold',
paddingTop: 30,
padding: 20,
textAlign: 'center',
backgroundColor: 'rgba(240,240,240,1)',
},
button: {
fontSize: 20,
backgroundColor: 'rgba(220,220,220,1)',
borderRadius: 4,
borderWidth: 1,
borderColor: 'rgba(80,80,80,0.5)',
overflow: 'hidden',
padding: 7,
},
header: {
textAlign: 'left',
},
feature: {
padding: 10,
borderTopWidth: 1,
borderBottomWidth: 1,
},
});
And my BgSoundPlayer file
import {Alert} from 'react-native';
import Sound from 'react-native-sound';
Sound.setCategory('Playback', true);
class BgSoundPlayer1 {
setSound(soundURL) {
try {
this.soundURL = soundURL;
if (soundURL.isRequire) {
this.soundRef = new Sound(soundURL.url, error =>
this.callback(error, this.soundRef),
);
} else {
this.soundRef = new Sound(soundURL.url, Sound.MAIN_BUNDLE, error =>
this.callback(error, this.soundRef),
);
}
} catch (error) {
console.log('SOUNDREFERROR::', error);
}
}
callback(error, sound) {
try {
if (error) {
Alert.alert('error', error.message);
return;
}
//this.soundURL.onPrepared && this.soundURL.onPrepared(sound);
sound.play(() => {
sound.release();
});
} catch (error) {
console.log('CALL_BACKERROR::', error);
}
}
getVolume() {
return this.soundRef?.getVolume();
}
increaseVolume(soundURL) {
console.log('CHECKREF', this.soundRef);
let sound = this.soundRef?.getVolume();
if (sound < 1 || sound == 1) {
this.soundRef?.setVolume(sound + 0.1);
}
}
decreaseVolume(soundURL) {
console.log('CHECKREF', this.soundRef);
let sound = this.soundRef?.getVolume();
if (sound > 0 || sound == 0) {
this.soundRef?.setVolume(sound - 0.1);
}
}
pouse() {
this.soundRef?.pause();
}
}
const BgSoundPlayer = new BgSoundPlayer1();
export default BgSoundPlayer;
So what is happening right now if, when I am playing one audio track and increasing decreasing volume of track its working fine
but problem occurre's when I play second track and decrease sound of first one, it dosent works it decrease volume of second track
but when I tried to debug problem, I got to know that my this.soundRef variable is taking the refrance of latest one sound, so how can solve this

React Native and map

I have an issue in my project. I want to show elements after I get them from the JSON. When I am trying to observe content of JSON I see it, but when I am trying to show it in my component it doesn't appear. Also debugger don't show any errors or problrms and app compiles sucessfully. I am really stuck, so I really need your help guys
App.js code:
import React, { Component } from 'react'
import { View, ScrollView, StyleSheet } from 'react-native'
import { Header, ImageCard } from './src/components/uikit'
const url = 'https://s3.eu-central-1.wasabisys.com/ghashtag/RNForKids/00-Init/data.json'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
title: 'STAR GATE',
data: []
};
}
componentDidMount = async () => {
try {
const response = await fetch(url)
const data = await response.json()
this.setState({ data })
}
catch (e) {
console.log(e)
throw e
}
}
render() {
const { title, data } = this.state
const { container } = style
return (
<View>
<Header title={title} />
<ScrollView>
<View style={container}>
{data.map(item => {
<ImageCard data={item} key={item.id} />
})
}
</View>
</ScrollView>
</View>
)
}
}
const style = StyleSheet.create({
container: {
marginTop: 30,
flexDirection: 'row',
flexWrap: 'wrap',
flexShrink: 2,
justifyContent: 'space-around',
marginBottom: 150,
backgroundColor: 'gold',
width: 150
}
})
My problem happens in App.js inside the
And ImageCard code:
import React from 'react'
import { Image, View, Text, StyleSheet } from 'react-native'
import { h, w } from '../../../constants'
const ImageCard = ({data}) => {
const {container, sub, h2, cover} = styles
const {image, name} = data
return (
<View style={container}>
<View style={sub}>
<Image
style={cover}
source={{
uri: image,
}}
/>
</View>
<Text style={h2}>{name.toUpperCase()}</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
width: w / 2.1,
paddingVertical: 10,
},
sub: {
padding:10,
shadowColor: 'black',
shadowRadius: 8,
shadowOffset: { width: 0, height: 5 },
shadowOpacity: 0.4,
},
h2: {
fontFamily: 'AvenirNext-DemiBold',
fontSize: 16,
alignSelf: 'center',
textAlign: 'center',
width: w / 2.4
},
cover: {
width: w / 2.4,
height: w * 0.63,
borderRadius: 10
}
})
export { ImageCard }
It should be ok, I made it by guide, but something went wrong.
It looks like you're not returning anything from map!
data.map(item => {
<ImageCard data={item} key={item.id} />
})
should become
data.map(item => {
return <ImageCard data={item} key={item.id} />
})
// OR
data.map(item => ( // <-- Note the bracket change
<ImageCard data={item} key={item.id} />
))

React Native Expo Camera - Invariant Violation error when trying to start the camera

I am trying to run the following code by I get an Invariant Violation error:
import React, { Component } from "react";
import { View, Text, TouchableOpacity } from "react-native";
import { Camera, MediaLibrary } from "expo";
import * as Permissions from 'expo-permissions';
class MyCam extends Component {
state = {
video: null,
picture: null,
recording: false
};
_saveVideo = async () => {
const { video } = this.state;
const asset = await MediaLibrary.createAssetAsync(video.uri);
if (asset) {
this.setState({ video: null });
}
};
_StopRecord = async () => {
this.setState({ recording: false }, () => {
this.cam.stopRecording();
});
};
_StartRecord = async () => {
if (this.cam) {
this.setState({ recording: true }, async () => {
const video = await this.cam.recordAsync();
this.setState({ video });
});
}
};
toogleRecord = () => {
const { recording } = this.state;
if (recording) {
this._StopRecord();
} else {
this._StartRecord();
}
};
render() {
const { recording, video } = this.state;
return (
<Camera
ref={cam => (this.cam = cam)}
style={{
justifyContent: "flex-end",
alignItems: "center",
flex: 1,
width: "100%"
}}
>
{video && (
<TouchableOpacity
onPress={this._saveVideo}
style={{
padding: 20,
width: "100%",
backgroundColor: "#fff"
}}
>
<Text style={{ textAlign: "center" }}>save</Text>
</TouchableOpacity>
)}
<TouchableOpacity
onPress={this.toogleRecord}
style={{
padding: 20,
width: "100%",
backgroundColor: recording ? "#ef4f84" : "#4fef97"
}}
>
<Text style={{ textAlign: "center" }}>
{recording ? "Stop" : "Record"}
</Text>
</TouchableOpacity>
</Camera>
);
}
}
class RecVideo extends Component {
state = {
showCamera: false
};
_showCamera = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status === "granted") {
this.setState({ showCamera: true });
}
};
render() {
const { showCamera } = this.state;
return (
<View
style={{
justifyContent: "center",
alignItems: "center",
flex: 1,
width: "100%"
}}
>
{showCamera ? (
<MyCam />
) : (
<TouchableOpacity onPress={this._showCamera}>
<Text> Show Camera </Text>
</TouchableOpacity>
)}
</View>
);
}
}
export default RecVideo;
This is the error: Invariant Violation
I found this piece of code in here: https://forums.expo.io/t/how-to-record-video/18834
I only made a change on how the permission are imported but the rest is the same.
I'm guessing the error is related to the import since that's what I found online but I don't know how to fix it because everything seems to be right.
import React from 'react';
import { Text, View, TouchableOpacity,Vibration } from 'react-native';
import * as Permissions from 'expo-permissions';
import { Camera } from 'expo-camera';
import { AsyncStorage } from 'react-native';
import { ToastAndroid } from 'react-native';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
const PATTERN = [1000, 2000, 3000];
export default class OpenCamera extends React.Component {
state = {
hasCameraPermission: null,
type: Camera.Constants.Type.back,
};
async componentDidMount() {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasCameraPermission: status === 'granted' });
}
// get the uri;
async clicked1() {
Vibration.vibrate(PATTERN)
if (this.camera) {
let photo = await this.camera.takePictureAsync();
console.log('array>>',photo)
console.log('image path>>>>>>>', photo.uri)
await AsyncStorage.setItem('image_path_key', photo.uri);
if(photo.uri!=null){
this.props._changeCameraVisbilty(false);
this.props._setImageData(photo.uri)
// this.props.navigation.goBack()
}else{
ToastAndroid.show('There some problem to taking a photo,please try again', ToastAndroid.SHORT);
}
}
};
// _closeCamera=()=>{
// }
// get the photo
async snapPhoto() {
console.log('Button Pressed');
if (this.camera) {
console.log('Taking photo');
const options = { quality: 1, base64: true, fixOrientation: true,
exif: true};
await this.camera.takePictureAsync(options).then(photo => {
photo.exif.Orientation = 1;
console.log(photo);
});
}
}
render() {
//const { navigate } = this.props.navigation;
const { hasCameraPermission } = this.state;
if (hasCameraPermission === null) {
return <View />;
} else if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
} else {
return (
<View style={{ flex: 1 }}>
<Camera style={{ flex: 1 }}
ref={ (ref) => {this.camera = ref} }
type={this.state.type} >
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
}}>
<TouchableOpacity
style={{
flex: 0.1,
alignSelf: 'flex-end',
alignItems: 'center',
}}
onPress={() => {
this.setState({
type:
this.state.type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back,
});
}}>
<Text style={{ fontSize: 18, marginBottom: 10, color: 'white' }}> Flip </Text>
</TouchableOpacity>
</View>
</Camera>
<View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>
<TouchableOpacity
onPress={this.clicked1.bind(this)} >
<Text style={{fontSize:hp('3%'),marginTop:hp('2.3%'),marginBottom:hp('2.3%')}}>Take photo</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
}
Open custom camera code

React Native Camera - Multiple Photos

I am currently using react-native-camera as a library to take pictures. I managed to show and hide a one and only camera component depending on a specific state. I am working on an app that has multiple buttons to take a picture, for example:
Button A (show camera -> take picture -> store value on local state A)
Button B (show camera -> take picture -> store value on local state B)
Button C (show camera -> take picture -> store value on local state C)
I have been breaking my head on how to do this, but can't figure it out.
My code is the following:
import React, { Component } from 'react';
import { StyleSheet, Text, TouchableOpacity, View, Button } from 'react-native';
import { RNCamera } from 'react-native-camera';
export default class BadInstagramCloneApp extends Component {
constructor(props){
super(props);
this.state = {
isVisible: false,
value1: null,
value2: null
}
}
render() {
return (
<View style={styles.subcontainer}>
{this.state.isVisible === true
?
<View style={styles.container}>
<RNCamera
ref={ref => {
this.camera = ref;
}}
style={styles.preview}
type={RNCamera.Constants.Type.back}
flashMode={RNCamera.Constants.FlashMode.on}
permissionDialogTitle={'Permission to use camera'}
permissionDialogMessage={'We need your permission to use your camera phone'}
onGoogleVisionBarcodesDetected={({ barcodes }) => {
console.log(barcodes);
}}
/>
<View style={{ flex: 0, flexDirection: 'row', justifyContent: 'center' }}>
<TouchableOpacity onPress={this.takePicture.bind(this)} style={styles.capture}>
<Text style={{ fontSize: 14 }}> SNAP </Text>
</TouchableOpacity>
</View>
</View>
:
<View>
<Button title='PHOTO 1' onPress={this.changeState}/>
<Button title='PHOTO 2' onPress={this.changeState2}/>
<Button title='SHOW RESULTS' onPress={this.showResults}/>
</View>
}
</View>
);
}
changeState = () =>{
this.setState({isVisible: true})
}
changeState2 = () =>{
this.setState({isVisible: true})
}
showResults = () => {
console.log('VALUE1: ' + this.state.value1);
console.log('VALUE2: ' + this.state.value2);
}
takePicture = async function() {
if (this.camera) {
const options = { quality: 0.5, base64: true };
const data = await this.camera.takePictureAsync(options);
console.log(data.uri);
this.setState({isVisible: false});
}
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'black'
},
subcontainer: {
flex: 1,
flexDirection: 'column',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
padding: 15,
paddingHorizontal: 20,
alignSelf: 'center',
margin: 20,
},
});
I would use the state to distinguish which "camera" you are using.
Your initial state:
this.state = {
isVisible: false,
pictureType: null,
value1: null,
value2: null
}
The function to call when a button is called, where each button has a different pictureType:
initTakingPicture = (pictureType) => {
this.setState({
isVisible: true,
pictureType: pictureType
})
}
Your example button:
<Button title='PHOTO 1' onPress={() => this.initTakingPicture("A")}/>
Then in your takePicture function you can check the state to distinguish which type of picture you are taking and save it into the according field:
takePicture = async function() {
if (this.camera) {
const options = { quality: 0.5, base64: true };
const data = await this.camera.takePictureAsync(options);
console.log(data.uri);
let fieldToSave = "value1" // Fallback
if (this.state.pictureType === "A") {
// Operation you need to do for pictureType A
fieldToSave = "value1"
} else if (this.state.pictureType === "B") {
// Operation you need to do for pictureType B
fieldToSave = "value2"
}
this.setState({
isVisible: false,
pictureType: null,
[fieldToSave]: data.uri
});
}
};

How to use realm in react native expo?

I want to use relamDb in my react native expo project. I run the following command to install realm in my project-
npm install --save realm
it doesn't show any error while installing. After installing, in my project I have created two classes - App.js and TodoListComponent.js
App.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import TodoListComponent from './components/TodoListComponent';
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<TodoListComponent/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
TodoListComponent.js
import React, { Component } from 'react';
import { View, FlatList, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';
import { updateTodoList, deleteTodoList, queryAllTodoLists } from '../databases/allSchemas';
import realm from '../databases/allSchemas';
import Swipeout from 'react-native-swipeout';
import HeaderComponent from './HeaderComponent';
import PopupDialogComponent from './PopupDialogComponent';
let FlatListItem = props => {
const { itemIndex, id, name, creationDate, popupDialogComponent, onPressItem } = props;
showEditModal = () => {
popupDialogComponent.showDialogComponentForUpdate({
id, name
});
}
showDeleteConfirmation = () => {
Alert.alert(
'Delete',
'Delete a todoList',
[
{
text: 'No', onPress: () => { },//Do nothing
style: 'cancel'
},
{
text: 'Yes', onPress: () => {
deleteTodoList(id).then().catch(error => {
alert(`Failed to delete todoList with id = ${id}, error=${error}`);
});
}
},
],
{ cancelable: true }
);
};
return (
<Swipeout right={[
{
text: 'Edit',
backgroundColor: 'rgb(81,134,237)',
onPress: showEditModal
},
{
text: 'Delete',
backgroundColor: 'rgb(217, 80, 64)',
onPress: showDeleteConfirmation
}
]} autoClose={true}>
<TouchableOpacity onPress={onPressItem}>
<View style={{ backgroundColor: itemIndex % 2 == 0 ? 'powderblue' : 'skyblue' }}>
<Text style={{ fontWeight: 'bold', fontSize: 18, margin: 10 }}>{name}</Text>
<Text style={{ fontSize: 18, margin: 10 }} numberOfLines={2}>{creationDate.toLocaleString()}</Text>
</View>
</TouchableOpacity>
</Swipeout >
);
}
export default class TodoListComponent extends Component {
constructor(props) {
super(props);
this.state = {
todoLists: []
};
this.reloadData();
realm.addListener('change', () => {
this.reloadData();
});
}
reloadData = () => {
queryAllTodoLists().then((todoLists) => {
this.setState({ todoLists });
}).catch((error) => {
this.setState({ todoLists: [] });
});
console.log(`reloadData`);
}
render() {
return (<View style={styles.container}>
<HeaderComponent title={"Todo List"}
hasAddButton={true}
hasDeleteAllButton={true}
showAddTodoList={
() => {
this.refs.popupDialogComponent.showDialogComponentForAdd();
}
}
/>
<FlatList
style={styles.flatList}
data={this.state.todoLists}
renderItem={({ item, index }) => <FlatListItem {...item} itemIndex={index}
popupDialogComponent={this.refs.popupDialogComponent}
onPressItem={() => {
alert(`You pressed item `);
}} />}
keyExtractor={item => item.id}
/>
<PopupDialogComponent ref={"popupDialogComponent"} />
</View>);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-start',
},
flatList: {
flex: 1,
flexDirection: 'column',
}
});
After these coding, when I run the application it shows the following error-
missing Realm constructor. Did you run "react-native link realm" ? Please see https://realm.io/docs/react-native/latest/#missing-realm-constructor for troubleshooting
I have tried to find out problem from the below links-
https://github.com/realm/realm-js/issues/1407
https://github.com/realm/realm-js/issues/1340
But none of these were helpful to me. So, it would be very nice if some one helps me to know how to use realmDb in React native expo project.
Expo does not support realm.
You will have to eject from expo and then start using realm
Please note that Expo does not support Realm, From the docs.
Old Question, but you can now by using their template:
https://www.npmjs.com/package/#realm/expo-template-ts
https://www.mongodb.com/docs/realm/sdk/react-native/quick-start-expo/

Categories

Resources