How to add event to Agenda react native calendar - javascript

My inquiry is about adding an item to the agenda by user input.
I'm working on a calendar app.
I'm brand new to react native.
Please refer to the code below:
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, StatusBar } from 'react-native';
import { Agenda } from 'react-native-calendars';
import { Card } from 'react-native-paper';
const timeToString = (time) => {
const date = new Date(time);
return date.toISOString().split('T')[0];
}
const Schedule = () => {
const [items, setItems] = React.useState({});
const loadItems = (day) => {
setTimeout(() => {
for (let i = -15; i < 85; i++) {
const time = day.timestamp + i * 24 * 60 * 60 * 1000;
const strTime = timeToString(time);
if (!items[strTime]) {
items[strTime] = [];
const numItems = Math.floor(Math.random() * 1 + 1);
for (let j = 0; j < numItems; j++) {
items[strTime].push({
name: 'Add your Agenda',
height: Math.max(10, Math.floor(Math.random() * 150)),
day: strTime
});
}
}
}
const newItems = {};
Object.keys(items).forEach(key => {
newItems[key] = items[key];
});
setItems(newItems);
}, 1000);
}
const renderItem = (item) => {
return (
<TouchableOpacity style={styles.item}>
<Card>
<Card.Content>
<View>
<Text>{item.name}</Text>
</View>
</Card.Content>
</Card>
</TouchableOpacity>
);
}
return (
<View style={styles.container}>
<Agenda
items={items}
loadItemsForMonth={loadItems}
selected={new Date()}
refreshControl={null}
showClosingKnob={true}
refreshing={false}
renderItem={renderItem}
/>
<StatusBar />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
item: {
flex: 1,
borderRadius: 5,
padding: 10,
marginRight: 10,
marginTop: 17
},
});
export default Schedule;
My objective is to utilize this modal to enter the event's details (say, the time, date, and title), click "Add," and then have those details posted to the agenda.

Related

Audio is not automatically closing while pressing backbutton in REACT NATIVE application

In a media player application, I try to use "expo-av" library to build a playlist. everything is working fine. But when I press on the backbutton, it is not behaving properly. I tried in many way. but nothing works for me.
I tried while handling backButton, like, sound.unloadAsync(), sound.stopAsync(), setSound(null).
import React, { useEffect, useState } from 'react';
import {
View,
BackHandler,
Text,
TouchableWithoutFeedback,
StyleSheet,
} from 'react-native';
import * as Progress from 'react-native-progress';
import { connect } from 'react-redux';
import { MaterialCommunityIcons } from '#expo/vector-icons';
import { Audio } from 'expo-av';
const sectionsAllCards = [
{
id: 'audio-01',
name: 'Body scan: Generic under mindfulness',
link: 'Bodyscan.m4a',
}
];
const MusicPlayerList = ({ navigation, route, ...props }) => {
const [isPlaying, setIsPlaying] = useState(false);
const [progress, setProgress] = useState(0);
const [audioIndex, setAudioIndex] = useState(0);
const [soundObject, setSoundObject] = useState(null);
const audioSources = [
require('../../assests/musics/Bodyscan.m4a')
];
const togglePlayback = async () => {
if (isPlaying) await soundObject.pauseAsync();
else await soundObject.playAsync();
setIsPlaying(!isPlaying);
};
const onPlaybackStatusUpdate = (status) => {
setProgress(status.positionMillis / status.durationMillis);
};
useEffect(() => {
const loadAudio = async () => {
const source = audioSources[audioIndex];
const sound = new Audio.Sound();
try {
await sound.loadAsync(source);
setSoundObject(sound);
sound.setOnPlaybackStatusUpdate(onPlaybackStatusUpdate);
} catch (error) {
console.log(error);
}
};
loadAudio();
}, [audioIndex]);
async function handleBackButtonClick() {
navigation.navigate('LoginSignup');
return true;
}
useEffect(() => {
BackHandler.addEventListener(
'hardwareBackPress',
handleBackButtonClick,
);
return () => {
BackHandler.removeEventListener(
'hardwareBackPress',
handleBackButtonClick,
);
};
}, []);
const handleOnPress = async (index) => {
if (index === audioIndex) togglePlayback();
else {
setIsPlaying(false);
setProgress(0);
await soundObject.stopAsync();
setSoundObject(null);
setAudioIndex(index);
}
};
return (
<View style={{ backgroundColor: '#efefef', flex: 1 }}>
{sectionsAllCards.map((card, index) => (
<TouchableWithoutFeedback
key={card.id}
onPress={() => handleOnPress(index)}
>
<View style={styles.boxContainer}>
<Text style={styles.audioText}>{card.name}</Text>
<View style={styles.audioIconContainer}>
{progress >= 0 && progress <= 1 && (
<View>
<Progress.Circle
style={styles.progress}
progress={audioIndex === index ? progress : 0}
indeterminate={false}
showsText={false}
size={60}
borderWidth={2}
color={'#479162'}
/>
<Text
style={{
position: 'absolute',
left: 11,
top: 10,
}}
>
<MaterialCommunityIcons
name={
isPlaying && audioIndex === index
? 'pause'
: 'play'
}
size={38}
style={{ color: '#479162' }}
/>
</Text>
</View>
)}
</View>
</View>
</TouchableWithoutFeedback>
))}
</View>
);
};
const styles = StyleSheet.create({
boxContainer: {
},
audioText: {
},
});
const mapStateToProps = (state) => ({
accessToken: state.auth.accessToken,
});
export default connect(mapStateToProps, {})(MusicPlayerList);

pass barcode data to another screen in react native

I am new to react native I want to ask that if i wanted to show the data from the barcode after scanned to another screen. how to do it here is my code
App.js
import Scanner from './jscan/Scanner';
import Home from './jscan/Home';
import{NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
import{createBottomTabNavigator} from '#react-navigation/bottom-tabs';
const Stack = createStackNavigator();
const Tab= createBottomTabNavigator();
function App(){
return(
<Stack.Navigator>
<Stack.Screen name="Home" component={Home}/>
<Stack.Screen name="Scanner" component={Scanner}/>
</Stack.Navigator>
);
}
export default () => {
return(
<NavigationContainer>
<App/>
</NavigationContainer>
)
}
here is my Home.js it is the place that i wanted to show my barcode data and also it is the first screen
Home.js
import {View,Text, Button, StyleSheet} from 'react-native';
import React, {useState,Component} from 'react';
import {useNavigation} from'#react-navigation/native';
import {StatusBar} from'expo-status-bar';
import Scanner from './Scanner';
export default function Home ({route}){
const navigation = useNavigation();
return(
<View style={styles.container}>
<Button title = 'Scan' onPress={()=> navigation.navigate('Scanner')}/>
<Text></Text>
<StatusBar style="auto"/>
</View>
);
}
const styles= StyleSheet.create({
container : {
flex:1,
backgroundColor:'#fff',
alignItems:'center',
justifyContent:'center'
}
})
here is the scanner
scanner.js
import React, { useState, useEffect,Component,onMount} from 'react';
import { Text,TextInput, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
import {useNavigation} from'#react-navigation/native';
import {StatusBar} from 'expo-status-bar';
export default function App() {
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
const [text, setText] = useState('Not yet scanned')
const [currentDate, setCurrentDate] = useState('');
const navigation = useNavigation();
const askForCameraPermission = () => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
})()
}
// Request Camera Permission
useEffect(() => {
askForCameraPermission();
}, []);
useEffect(() => {
var date = new Date().getDate(); //Current Date
var month = new Date().getMonth() + 1; //Current Month
var year = new Date().getFullYear(); //Current Year
var hours = new Date().getHours(); //Current Hours
var min = new Date().getMinutes(); //Current Minutes
var sec = new Date().getSeconds(); //Current Seconds
setCurrentDate(
date + '/' + month + '/' + year
+ ' ' + hours + ':' + min + ':' + sec
);
}, []);
// What happens when we scan the bar code
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true);
setText(data +'\n'+ currentDate)
};
// Check permissions and return the screens
if (hasPermission === null) {
return (
<View style={styles.container}>
<Text>Requesting for camera permission</Text>
</View>)
}
if (hasPermission === false) {
return (
<View style={styles.container}>
<Text style={{ margin: 10 }}>No access to camera</Text>
<Button title={'Allow Camera'} onPress={() => askForCameraPermission()} />
</View>)
}
// Return the View
return (
<View style={styles.container}>
<View style={styles.barcodebox}>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={{ height: 400, width: 400 }} />
</View>
<Text style={styles.maintext}>{text}</Text>
{
scanned && <Button title={'Scan again?'} onPress={() => setScanned(false)} color='tomato' />
}
{
scanned && <Button title={'OK'} onPress={()=> navigation.navigate('Home')} />
}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
maintext: {
fontSize: 16,
margin: 20,
},
barcodebox: {
alignItems: 'center',
justifyContent: 'center',
height: 300,
width: 300,
overflow: 'hidden',
borderRadius: 30,
backgroundColor: 'tomato'
}
});
I have tried some method from other source but it still cant work with it. hope u guys help thanks
You can pass the data to Home screen with params.
Scanner.js:
// Pass the text parameter as a second argument to navigate function
<Button title={'OK'} onPress={()=> navigation.navigate('Home', { text })} />
Home.js:
// Accessing the passed parameter
export default function Home ({ route }){
...
return (
...
<Text>{route.params && route.params.text}</Text>
...
)
}
Check out react-navigation documentation for more info:
https://reactnavigation.org/docs/params/

Smooth scrollToOffset in FlatList React Native

I have tried to sychronise-scroll two Flatlist with state but my thought was that scrolling was shaking, lagging and not smooth due to re-rendering. But I tried with referencing React element but it didn't help. The result is the same, scrolling is like a person gotten electrified and shock, that is, shaking.
Code is below:
import * as React from 'react';
import { Text, View, StyleSheet, FlatList, Button } from 'react-native';
import Constants from 'expo-constants';
export default function App() {
const listRefOne = React.useRef();
const listRefTwo = React.useRef();
const handleRef = (listRef, offset) => {
if (listRef === listRefOne) {
listRefTwo.current.scrollToOffset({ animated: true, offset: offset });
console.log('One', offset);
}
if (listRef === listRefTwo) {
listRefOne.current.scrollToOffset({ animated: true, offset: offset });
console.log('Two', offset);
}
};
return (
<View style={styles.container}>
<MyListView listRef={listRefOne} handleRef={handleRef} />
<MyListView listRef={listRefTwo} handleRef={handleRef} />
</View>
);
}
const generateData = () => {
const temp = [];
for (var i = 1; i <= 100; i++) {
temp.push({ id: i, title: `# ${i} Hello` });
}
return temp;
};
const mydata = generateData();
const MyListView = ({ listRef, handleRef }) => {
const handleScroll = (offset) => handleRef(listRef, offset);
return (
<FlatList
ref={(list) => {
listRef.current = list;
}}
style={styles.itemView}
data={mydata}
renderItem={({ item }) => (
<Text style={{ fontSize: 20 }}>{item.title}</Text>
)}
keyExtractor={(item) => item.id}
onScroll={(e) => handleScroll(e.nativeEvent.contentOffset.y)}
/>
);
};
const styles = StyleSheet.create({
container: {
flex: 2,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
itemView: {
flexGrow: 1,
backgroundColor: '#efefef',
margin: 3,
},
});
Expo Link

React-native component not working which loops through and shows increasing value on UI

I am trying to build a component where I am trying to update a view in for loop to render the value on UI,
Pseudo code of what I am trying to implement:
1.for 1..100
Increment : var + 1
Do update the View to update var value
Note : I want the visuals of the incrementing values.
Below code have written till now, not getting any more leads on it. Please guide me on this.
export default class App extends React.Component {
state = {
amount: 45,
}
increaseAmount = () => {
for (var i = 0; i < 10; i++) {
let amt = this.state.amount + 1;
setTimeout(() => {
this.setState({
timePassed: true,
amount: amt
})
}, 100);
}
};
render() {
return ( <
View style = {
styles.container
} >
<
Text > Hello World {
this.state.amount
} < /Text> <
Button title = "Click me"
onPress = {
() => this.increaseAmount()
} > < /Button> <
/View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems:'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
});
Thanks in Advance.
increaseAmount = () => {
let myInterval;
myInterval = setInterval(() => {
if (this.state.amount === 99)
clearInterval(myInterval);
this.setState({
timePassed: true,
amount: this.state.amount + 1
})
}, 100);
};
You can achieve that with Animated:
import { Animated, Text, View } from "react-native";
export default class Counter extends React.Component {
constructor(props) {
super(props);
const amount = 45;
this.animatedAmount = new Animated.Value(amount);
this.animatedAmount.addListener(this.onAmountChange);
this.state = { amount };
}
increaseAmount = (amount) => {
Animated.timing(this.animatedAmount, {
duration: 1000,
toValue: this.state.amount + amount,
useNativeDriver: true
}).start();
};
onAmountChange = (e) => {
this.setState({
amount: Math.floor(e.value)
});
};
render() {
return (
<View style={styles.container}>
<Text> Hello World {this.state.amount} </Text>{" "}
<Button title="Click me" onPress={() => this.increaseAmount(45)}>
{""}
</Button>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
paddingTop: Constants.statusBarHeight,
backgroundColor: "#ecf0f1",
padding: 8
}
});

React-Native ListView of Switches does not update

Situation: I have a ListView of Switches
Problem: Switches dont change its state when they are pressed, debugging each switch goes to checked but after setValue ends the switch comes back to unchecked. Switches are never being rendered as checked
Here is my code:
import React, { Component } from 'react';
import {
StyleSheet,
View,
Switch,
ListView
} from 'react-native';
export default class FriendListBody extends Component {
constructor(props) {
super(props);
let friends = this.props.friends.map((friend) => {
return {
...friend,
selected: false
}
});
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.state = {
datasource: ds.cloneWithRows(friends),
friends
};
this._renderRow= this._renderRow.bind(this);
this._setValue = this._setValue.bind(this);
}
render() {
return (
<View style={styles.container}>
<ListView
dataSource={this.state.datasource}
renderRow={this._renderRow}
style={styles.listView}
enableEmptySections={true}
/>
</View>
);
}
_setValue(id, value) {
let newList = this.state.friends.slice();
let pos = -1;
for (let i = 0; i < this.state.friends.length; i++) {
if (id === this.state.friends[i]._id) {
pos = i;
break;
}
}
newList[pos].selected = value;
this.setState({
friends: newList,
datasource: this.state.datasource.cloneWithRows(newList) }
);
}
_renderRow(rowData) {
return (
<View key={rowData._id} style={{ borderRadius: 10 }}>
<Switch
onValueChange={(value) => this._setValue(rowData._id, value)}
style={{ marginBottom: 10 }}
value={ rowData.selected } />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#d9d9d9',
},
listView: {
flex: 1,
borderColor: 'grey'
}
});
Somethings that paid my attention is that _renderRow method is called only once, when list is loaded for the first time.
Thanks for helping.
If you want to update listView, create new objects instead of updating the properties of existing objects.
import React, { Component } from 'react';
import {
StyleSheet,
View,
Switch,
ListView
} from 'react-native';
export default class FriendListBody extends Component {
ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
constructor(props) {
super(props);
let friends = this.props.friends.map((friend) => {
return {
...friend,
selected: false
}
});
this.state = {
datasource: this.ds.cloneWithRows(friends),
friends
};
this._renderRow= this._renderRow.bind(this);
this._setValue = this._setValue.bind(this);
}
render() {
return (
<View style={styles.container}>
<ListView
dataSource={this.state.datasource}
renderRow={this._renderRow}
style={styles.listView}
enableEmptySections={true}
/>
</View>
);
}
_setValue(id, value) {
let newList = this.state.friends.slice();
let pos = -1;
for (let i = 0; i < this.state.friends.length; i++) {
if (id === this.state.friends[i]._id) {
pos = i;
break;
}
}
newList[pos].selected = value;
const datasource = this.ds.cloneWithRows(newList);
this.setState({
friends: newList,
datasource: datasource
);
}
_renderRow(rowData) {
return (
<View key={rowData._id} style={{ borderRadius: 10 }}>
<Switch
onValueChange={(value) => this._setValue(rowData._id, value)}
style={{ marginBottom: 10 }}
value={ rowData.selected } />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#d9d9d9',
},
listView: {
flex: 1,
borderColor: 'grey'
}
});

Categories