Onpress method does not work in React Native? - javascript

I am getting an error that I do not understand when using the useState and useSetState functions that I sent as prop to the component I created.
Here is the main component which the CalcButton placed:
export const Calculator = () => {
const [operationText, setOperationText] = React.useState('');
const [operationHistory, setOperationHistory] = React.useState([]);
return (
<SafeAreaView>
<CalcButton operationText={operationText} setOperationText={setOperationText} />
</SafeAreaView>
);
};
Calcbutton.tsx Component
export default function CalcButton(
operationText,
setOperationText,
) {
const handleClick = () => {
setOperationText('2')
};
return (
<View style={styles.container}>
<TouchableOpacity onPress={handleClick} style={styles.inner}>
<View style={styles.middleInner}>
<Text style={styles.label}>=</Text>
</View>
</TouchableOpacity>
</View>
);
}
[enter image description here][1]
When I click CalcButton it gives that error.
https://i.stack.imgur.com/FFfYl.png
Thanks for all helps!

In CalcButton component I added curly braces to my props and it works
export default function CalcButton(
{operationText,
setOperationText}
) {
const handleClick = () => {
setOperationText('2')
};
return (
<View style={styles.container}>
<TouchableOpacity onPress={handleClick} style={styles.inner}>
<View style={styles.middleInner}>
<Text style={styles.label}>=</Text>
</View>
</TouchableOpacity>
</View>
);
}

Related

How can we pass data from the main function to the secondary function? React-Native

I want to pass a value from my parent function to my child function.
but I don't know what to do.
please help advice
The language I use is react native. I want to send search data to main function
this is my code
Main Function
export default function Home() {
return (
<View>
<HeaderHome Upload={Upload} Uri={Uri} />
</View>
);
}
Second Function
export default function HeaderHome({ Upload, Uri }) {
const navigation = useNavigation();
const [showScrollView, setShowScrollView] = useState(false);
const [search, setSearch] = useState('');
const onPress = () => {
setShowScrollView(!showScrollView);
};
console.log(search);
return (
<View>
{showScrollView ? (
<View>
<TextInput
placeholder="Search..."
placeholderTextColor="#000"
onChangeText={(e) => setSearch(e)}
/>
<TouchableOpacity onPress={() => onPress()}>
<Text>Cancel</Text>
</TouchableOpacity>
</View>
) : (
<View>
<View>
<Ionicons
name="md-search"
style={styles.iconSearch}
onPress={() => onPress()}
/>
<Ionicons
name="person-circle"
onPress={() => navigation.navigate('Menu', { Upload, Uri })}
/>
</View>
</View>
)}
</View>
);
}
Create a callback function that you pass as a prop from Home to HeaderHome. This could look as follows.
export default function Home() {
const [search, setSearch] = useState('')
return (
<View>
<HeaderHome setHomeSearch={setSearch} Upload={Upload} Uri={Uri} />
</View>
);
}
In HeaderHome you can call that function in the onPress function and set the state search in the Home component as follows.
export default function HeaderHome({ Upload, Uri, setHomeSearch }) {
const navigation = useNavigation();
const [showScrollView, setShowScrollView] = useState(false);
const [search, setSearch] = useState('');
const onPress = () => {
setShowScrollView(!showScrollView);
};
console.log(search);
const onSearchSet = (text) => {
setSearch(text)
setHomeSearch(text)
}
return (
<View>
{showScrollView ? (
<View>
<TextInput
placeholder="Search..."
placeholderTextColor="#000"
onChangeText={(e) => onSearchSet(e)}
/>
<TouchableOpacity onPress={() => onPress()}>
<Text>Cancel</Text>
</TouchableOpacity>
</View>
) : (
<View>
<View>
<Ionicons
name="md-search"
style={styles.iconSearch}
onPress={() => onPress()}
/>
<Ionicons
name="person-circle"
onPress={() => navigation.navigate('Menu', { Upload, Uri })}
/>
</View>
</View>
)}
</View>
);
}

react-native how to change usestate data getting from other page?

i'm beginner of react-native. help me haha...
i give a useState data ('playlist') from MainPage.js to playList.js
in MainPage.js
const [playList, setPlayList] = useState([]);
<TouchableOpacity onPress={() => navigate('PlayList', {data: playList})}>
in playList.js
const Imagetake = ({url}) => {
url =url.replace('{w}', '100');
url = url.replace('{h}', '100');
return <Image style ={{height:'100%', width:'100%'}} source ={{url:url}}/>
};
const PlayList = ({ navigation }) => {
const playList = navigation.getParam('data');
const setPlayList = navigation.getParam('setData');
const deletePlayList = (data) => {
setPlayList(playList.filter((song)=> song.id != data.id));
};
return (
<View style={styles.posts}>
<FlatList
data={playList}
keyExtractor={posts => posts.id}
renderItem={({item}) =>{
return (
<View>
<TouchableOpacity onPress={() => deletePlayList( item )}>
<Ionicons name="trash-outline" size={30}/>
</TouchableOpacity>
<TouchableOpacity>
<View style={styles.post}>
<View style ={styles.postcontent}>
<Imagetake url={item.attributes.artwork.url}></Imagetake>
</View>
<View style={styles.posthead}>
<View style = {styles.postheadtext}>
<Text style ={styles.posttitletext}>{item.attributes.name}</Text>
<Text style={styles.username}>{item.attributes.artistName}</Text>
</View>
<View style = {styles.postheadtext2}>
<Text style={styles.username}>{item.attributes.albumName}</Text>
</View>
</View>
</View>
</TouchableOpacity>
</View>
)
}}
/>
</View>
);
};
when i delete some songs in playList, it is well done in playList page. but when i go to mainpage and go to playList again, delete is useless. the songs that i deleted before is refreshed. how can i fix it? T^T
You may also pass the setPlayList function to PlayList page.
And instead of creating another useState in the child page, you directly call the setPlayList that is passed from parent page

React Native: FlatList Opens Modal for all Items Instead of Selected Item

I am using React Native FlatList and React Native Modal.
Upon clicking on the item from the FlatList, I want to view 1 Modal only (containing the details of the item selected).
However, if there are 4 items in the FlatList, selecting 1 item causes
all 4 modals to pop up.
Is there anyway I can display only 1 modal for 1 selected item in the FlatList instead of multiple modal?
Code Snippet below (some lines of code were removed as it's not needed):
constructor(props) {
super(props);
this.state = {
dataSource: [],
isLoading: true,
modalVisible: false,
}
}
setModalVisible = (visible) => {
this.setState({ modalVisible: visible });
}
viewModal(item, price) {
const { modalVisible } = this.state;
return (
<Modal
statusBarTranslucent={true}
animationType={"slide"}
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
}}
>
<View>
<View>
<View>
<Text>
Appointment Start Time:
</Text>
<Text>
{moment(item.time_start).format('h:mm a')}
</Text>
</View>
<View>
<Text>
Appointment End Time:
</Text>
<Text>
{moment(item.end_start).format('h:mm a')}
</Text>
</View>
<View style={styles.row}>
<Text>
Total:
</Text>
<Text>
{price}
</Text>
</View>
<View>
<View>
<Button
mode="outlined"
onPress={() => {
this.setModalVisible(!modalVisible);
}}
>
{'Cancel'}
</Button>
</View>
<View>
<Button
mode="contained"
onPress={() => {
this.setModalVisible(!modalVisible);
}}
>
{'Accept'}
</Button>
</View>
</View>
</View>
</View>
</Modal>
);
}
viewFreelancerTime() {
return (
<View>
<FlatList
renderItem={({ item }) => {
let totalPrice = (parseFloat(item.service_price) + parseFloat(item.service_deposit)).toFixed(2);
return (
<Container>
{this.viewModal(item, totalPrice)}
<TouchableNativeFeedback
onPress={() => {
this.setModalVisible(true);
}}
>
<View>
<View>
<Text>
{moment(item.time_start).format('h:mm a')}
</Text>
</View>
<View>
<Text>
{totalPrice}
</Text>
</View>
</View>
</TouchableNativeFeedback>
</Container>
);
}}
/>
</View>
);
}
render() {
return (
<>
<View style={{ flex: 1 }}>
{this.viewFreelancerTime()}
</View>
</>
);
};
The poblem is that you are rendering the modal in the renderItem method, so every time you select an item, the modal will open in each rendered item.
To solve that you will have to render a custom Modal component with an absolute position at the same level of your FlatList, and pass the selected item information as props.
UPDATE
Just something like this:
import React, {useState} from "react";
import { Modal } from "react-native";
export default function MyFlatList(props) {
const [selectedItem, setSelectedItem] = useState(null);
const handleOnSelectItem = (item) => {
setSelectedItem(item);
};
const handleOnCloseModal = () => {
setSelectedItem(null);
};
renderItem = ({ item }) => {
return (
<Container>
<TouchableNativeFeedback onPress={() => handleOnSelectItem(item)}>
<View>
<View>
<Text>{moment(item.time_start).format("h:mm a")}</Text>
</View>
<View>
<Text>{totalPrice}</Text>
</View>
</View>
</TouchableNativeFeedback>
</Container>
);
};
return (
<View>
<FlatList renderItem={this.renderItem} />
<CustomModal isVisible={selectedItem} selectedItem={selectedItem} onClose={handleOnCloseModal} />
</View>
);
}
export function CustomModal(props) {
const { isVisible, item, onClose, /*...*/ } = props;
// Play with the item data
let totalPrice = (
parseFloat(item.servicePrice) + parseFloat(item.serviceDeposit)
).toFixed(2);
return <Modal visible={isVisible} onRequestClose={onClose}>{/*...*/}</Modal>; // Render things inside the data
}
I suggest you to do a pagination and play with FlatList native props if you are going to implement an infinite scroll.
Pd: to reduce re-renders because of state updates, I am reusing the selectedItem state, so if it is not null then the modal will be visible

React Native Swipeable close after onPress not working

So I've seen many posting the same problem, but for some I don't seem to be able to adapt the posted solutions to my case.. I hope someone can tell me exactly what changes I need to do in order to get this working, since I don't know how to implement the suggested solutions!
I am using React Native Swipeable
Example of someone having the same issue
I have a file in which I built the Swipeable Component and an other class which calls the component. I've set a timeout close function on the onSwipeableOpen as a temporary solution. But ideally it should close immediately upon pressing "delete". The "..." stands for other code which I deleted since it's not important for this case.
AgendaCard.js
...
const RightActions = ({ onPress }) => {
return (
<View style={styles.rightAction}>
<TouchableWithoutFeedback onPress={onPress}>
<View style={{ flexDirection: "row", alignSelf: "flex-end" }}>
<Text style={styles.actionText}>Löschen</Text>
<View style={{ margin: 5 }} />
<MaterialIcons name="delete" size={30} color="white" />
</View>
</TouchableWithoutFeedback>
</View>
);
};
...
export class AgendaCardEntry extends React.Component {
updateRef = (ref) => {
this._swipeableRow = ref;
};
close = () => {
setTimeout(() => {
this._swipeableRow.close();
}, 2000);
};
render() {
return (
<Swipeable
ref={this.updateRef}
renderRightActions={() => (
<RightActions onPress={this.props.onRightPress} />
)}
onSwipeableOpen={this.close}
overshootRight={false}
>
<TouchableWithoutFeedback onPress={this.props.onPress}>
<View style={styles.entryContainer}>
<Text style={styles.entryTitle}>{this.props.item.info}</Text>
<Text style={styles.entryTime}>
eingetragen um {this.props.item.time} Uhr
</Text>
</View>
</TouchableWithoutFeedback>
</Swipeable>
);
}
}
Agenda.js
...
renderItem(item) {
...
<AgendaCardAppointment
item={item}
onRightPress={() => firebaseDeleteItem(item)}
/>
...
}
I'm having the same issue and have been for days. I was able to hack through it, but it left me with an animation I don't like, but this is what I did anyways.
export class AgendaCardEntry extends React.Component {
let swipeableRef = null; // NEW CODE
updateRef = (ref) => {
this._swipeableRow = ref;
};
close = () => {
setTimeout(() => {
this._swipeableRow.close();
}, 2000);
};
onRightPress = (ref, item) => { // NEW CODE
ref.close()
// Delete item logic
}
render() {
return (
<Swipeable
ref={(swipe) => swipeableRef = swipe} // NEW CODE
renderRightActions={() => (
<RightActions onPress={() => this.onRightPress(swipeableRef)} /> // NEW CODE
)}
onSwipeableOpen={this.close}
overshootRight={false}
>
<TouchableWithoutFeedback onPress={this.props.onPress}>
<View style={styles.entryContainer}>
<Text style={styles.entryTitle}>{this.props.item.info}</Text>
<Text style={styles.entryTime}>
eingetragen um {this.props.item.time} Uhr
</Text>
</View>
</TouchableWithoutFeedback>
</Swipeable>
);
}
}

Undefined is not an object evaluating this.state/this.props

How do I bind a function outside of scope in React Native? I'm getting the errors:
undefined is not an object evaluating this.state
&
undefined is not an object evaluating this.props
I'm using the render method to evoke renderGPSDataFromServer() when the data has been loaded. The problem is, I'm trying to use _buttonPress() and calcRow() inside of renderGPSDataFromServer(), but I'm getting those errors.
I've added
constructor(props) {
super(props);
this._buttonPress = this._buttonPress.bind(this);
this.calcRow = this.calcRow.bind(this);
to my constructor and I've changed _buttonPress() { to _buttonPress = () => { and still nothing.
I think I understand the problem but I don't know how to fix it:
renderLoadingView() {
return (
<View style={[styles.cardContainer, styles.loading]}>
<Text style={styles.restData}>
Loading ...
</Text>
</View>
)
}
_buttonPress = () => {
this.props.navigator.push({
id: 'Main'
})
}
renderGPSDataFromServer =() => {
const {loaded} = this.state;
const {state} = this.state;
return this.state.dataArr.map(function(data, i){
return(
<View style={[styles.cardContainer, styles.modularBorder, styles.basePadding]} key={i}>
<View style={styles.cardContentLeft}>
<TouchableHighlight style={styles.button}
onPress={this._buttonPress().bind(this)}>
<Text style={styles.restData}>View Video</Text>
</TouchableHighlight>
</View>
<View style={styles.cardContentRight}>
<Text style={styles.restData}>{i}</Text>
<View style={styles.gpsDataContainer}>
<Text style={styles.gpsData}>
{Number(data.lat).toFixed(2)}</Text>
<Text style={styles.gpsData}>{Number(data.long).toFixed(2)}</Text>
</View>
<Text style={styles.gpsData}>
{this.calcRow(55,55).bind(this)}
</Text>
</View>
</View>
);
});
}
render = ()=> {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return(
<View>
{this.renderGPSDataFromServer()}
</View>
)
}};
How do I go about fixing this and in this case what is the problem?
this.props are read-only
React docs - component and props
And therefore a component shouldn't try a to modify them let alone mutate them as you are doing here:
_buttonPress = () => {
this.props.navigator.push({
id: 'Main'
})
}
I'd suggest using state instead:
_buttonPress = () => {
this.setState = {
...this.state,
navigator: {
...this.state.navigator,
id: 'Main'
}
}
}
Regarding your binding issue:
the .map method takes a 2nd argument that is used to set the value of this when the callback is invoked.
In the context of your question, you just need to pass thisas the 2nd argument to you .map method to bind the components scope's this to it.
This is happening because, the function inside the map method creates a different context. You can use arrow functions as the callback in the map method for lexical binding. That should solve the issue you are having.
renderGPSDataFromServer =() => {
const {loaded} = this.state;
const {state} = this.state;
return this.state.dataArr.map((data, i) => {
return(
<View style={[styles.cardContainer, styles.modularBorder, styles.basePadding]} key={i}>
<View style={styles.cardContentLeft}>
<TouchableHighlight style={styles.button}
onPress={this._buttonPress().bind(this)}>
<Text style={styles.restData}>View Video</Text>
</TouchableHighlight>
</View>
<View style={styles.cardContentRight}>
<Text style={styles.restData}>{i}</Text>
<View style={styles.gpsDataContainer}>
<Text style={styles.gpsData}>
{Number(data.lat).toFixed(2)}</Text>
<Text style={styles.gpsData}>{Number(data.long).toFixed(2)}</Text>
</View>
<Text style={styles.gpsData}>
{this.calcRow(55,55).bind(this)}
</Text>
</View>
</View>
);
});
}
Also, once you've used arrow functions in the class function definition you
don't need to bind them in constructor like:
constructor(props) {
super(props);
this._customMethodDefinedUsingFatArrow = this._customMethodDefinedUsingFatArrow.bind(this)
}
Also, once you have defined class functions as arrow functions, you
don't need to use the arrow functions while calling them either:
class Example extends React.Component {
myfunc = () => {
this.nextFunc()
}
nextFunc = () => {
console.log('hello hello')
}
render() {
// this will give you the desired result
return (
<TouchableOpacity onPress={this.myFunc} />
)
// you don't need to do this
return (
<TouchableOpacity onPress={() => this.myFunc()} />
)
}
}
not sure if this is the problem, but I think is code is wrong, and may be potentially causing your issue.
<View style={styles.cardContentLeft}>
<TouchableHighlight style={styles.button}
onPress={this._buttonPress().bind(this)}>
<Text style={styles.restData}>View Video</Text>
</TouchableHighlight>
</View>
specifically this line onPress={this._buttonPress().bind(this)}>
you are invoking the function and binding it at the same time.
The correct way to do this would be so
onPress={this._buttonPress.bind(this)}>
this way the function will be called only onPress.
You are going in the right direction, but there is still a minor issue. You are passing a function to your map callback that has a different scope (this) than your component (because it is not an arrow function), so when you do bind(this), you are rebinding your callback to use the scope from map. I think this should work, it basically turns the callback that you pass to map into an arrow function. Also, since you bind your function in the constructor, you do not need to do it again:
// The constructor logic remains the same
// ....
renderLoadingView() {
return (
<View style={[styles.cardContainer, styles.loading]}>
<Text style={styles.restData}>
Loading ...
</Text>
</View>
)
}
_buttonPress = () => {
this.props.navigator.push({
id: 'Main'
})
}
renderGPSDataFromServer =() => {
const {loaded} = this.state;
const {state} = this.state;
return this.state.dataArr.map((data, i) => {
return(
<View style={[styles.cardContainer, styles.modularBorder, styles.basePadding]} key={i}>
<View style={styles.cardContentLeft}>
<TouchableHighlight style={styles.button}
onPress={this._buttonPress}>
<Text style={styles.restData}>View Video</Text>
</TouchableHighlight>
</View>
<View style={styles.cardContentRight}>
<Text style={styles.restData}>{i}</Text>
<View style={styles.gpsDataContainer}>
<Text style={styles.gpsData}>
{Number(data.lat).toFixed(2)}</Text>
<Text style={styles.gpsData}>{Number(data.long).toFixed(2)}</Text>
</View>
<Text style={styles.gpsData}>
{this.calcRow(55,55).bind(this)}
</Text>
</View>
</View>
);
});
}
render = ()=> {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return(
<View>
{this.renderGPSDataFromServer()}
</View>
)
}};

Categories