I'm trying to use a touchablehighlight component and when I press it, nothing happens. So I changed it to a button and added a console log and still, react native won't register the press.
I'm using expo and I'm relatively new to react native.
Please tell me what I'm doing wrong
import React, { useState } from "react";
import {
Button,
Modal,
StyleSheet,
Text,
TouchableHighlight,
View,
} from "react-native";
const customPicker = (props) => {
const [selectedNumber, setSelectedNumber] = useState(props.pickerValues[0]);
const [pickerDisplayed, setPickerDisplayed] = useState(false);
function changeSelectedNumber(value) {
setSelectedNumber(value);
setPickerDisplayed(false);
}
const touchableHighlightcomponent = props.pickerValues.map((value, index) => (
<TouchableHighlight
style={styles.th}
onPress={() => changeSelectedNumber({ value })}
key={index}
>
<Text>{value}</Text>
</TouchableHighlight>
));
return (
<View>
<Button onPress={() => console.log("pressed")} title="one"></Button>
{/* <TouchableHighlight style={styles.input} onPress={() => this.console.log("pressed")}>
<Text>{selectedNumber}</Text>
</TouchableHighlight> */}
<Modal visible={() => pickerDisplayed} transparent={true}>
<View style={styles.picker}>
<View style={styles.pickerItems}>
<Text>Please select a value</Text>
{touchableHighlightcomponent}
</View>
</View>
</Modal>
</View>
);
};
I have discovered the problem.
It's a bug with the iOS simulator, it doesn't register button pushes.
To fix: Simply restart the iOS simulator
Related
I'm trying to use Async Storage for a note app, I created a component called task.js as a template for todos, an navigation.js component for nav, and home.js for the main screen all display with <navigation /> inapp.js, I added a funcction to store object value using async storage, but is not working, everytime I hard reload the app everything will be gone but it is not giving me any errors, I don't know where to start
here is my Home.js
import React, {useState} from 'react';
import { Keyboard, KeyboardAvoidingView, Platform, StyleSheet, Text,
TextInput, TouchableOpacity, View, SafeAreaView, ScrollView, Image } from 'react-native';
import Task from '../components/Task';
import AsyncStorage from '#react-native-async-storage/async-storage';
export default function Home({ navigation }) {
const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);
React.useEffect ( () => {
save(taskItems);
}, [taskItems])
React.useEffect (() => {
getsave();
}, [])
const handleAddTask = () => {
Keyboard.dismiss();
setTaskItems([...taskItems, task])
setTask(null);
}
const completeTask = (index) => {
let itemsCopy = [...taskItems];
itemsCopy.splice (index, 1);
setTaskItems(itemsCopy)
}
const save = async taskItems =>{
try {
const savetask = JSON.stringify(taskItems)
await AsyncStorage.setItem('tasksave', savetask)
} catch (e) {
console.log(e);
}
};
const getsave = async () => {
try {
const taskItems = await AsyncStorage.getItem('tasksave');
if (taskItems != null){
setTaskItems(JSON.parse(taskItems));
}
} catch (error) {
console.log(e);
}
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.tasksWrapper}>
<Text style={styles.sectionTitle}>Your stuff:</Text>
<TouchableOpacity onPress={() => navigation.navigate('About')}>
<Text style={styles.about}>About</Text>
</TouchableOpacity>
<ScrollView style={styles.items}>{
taskItems.map((item, index) => {
return (
<View key={index}>
<TouchableOpacity onPress={ () => navigation.navigate("Gas", {item})}>
<Task text={item} navigation={navigation} />
</TouchableOpacity>
<TouchableOpacity onPress={() => completeTask(index)} style={styles.deleteW}>
<Image style={styles.delete} source={require('../components/remove.png')}></Image>
</TouchableOpacity>
</View>
)
})
}
</ScrollView>
</View>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.textwrapper}>
<TextInput style={styles.input} placeholder={'message'} value={task} onChangeText={text => setTask(text)}></TextInput>
<TouchableOpacity onPress={() => handleAddTask()}>
<View style={styles.addWrap}>
<Text style={styles.add}>+</Text>
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
Here's my Task.js:
import React from "react";
import { View, Text, StyleSheet, Image, TouchableOpacity } from "react-native";
const Task = (props, {navigation}) => {
return (
<View style={styles.item}>
<View style={styles.itemleft}>
<Image style={styles.lightball} source={require('./arabic.png')}></Image>
<Text style={styles.itemtext}>{props.text}</Text>
</View>
<Image style={styles.arrow} source={require('./rightarrow.png')}></Image>
</View>
)
}
const styles = StyleSheet.create({
export default Task;
I hope is a quick read, I took out all the style stuff but this is still kinda long sorry, if you think it has something to do with my app.js or nav.js I can give you those too, I usually slove these bugs on my own but I just have no idea where to begin cause I'm not getting any error messages, thank you
As the title suggests, I am struggling to find a way to make my touchable opacities have a display of none by default (well, I suppose that is easy enough with a styling of display: none), but I'm not able to figure out how to toggle that using a touchable opacity.
In my head, the logic is to have the state change from true to false onpress, and false is visible while true is invisible. However, I can't muster up the knowledge to code it out. Here is what I have so far, more info below code:
import React, {useState} from 'react';
import { KeyboardAvoidingView, StyleSheet, Text, View, TextInput, TouchableOpacity, Keyboard, ImageBackground } from 'react-native';
import Task from './components/task';
const plus = {uri: 'https://media.discordapp.net/attachments/639282516997701652/976293252082839582/plus.png?width=461&height=461'};
const done = {uri: 'https://media.discordapp.net/attachments/736824455170621451/976293111456231434/done.png?width=461&height=461'};
const exit = {uri: 'https://media.discordapp.net/attachments/639282516997701652/976293251759898664/exit.png?width=461&height=461'};
const cog = {uri: 'https://media.discordapp.net/attachments/639282516997701652/976293672884789288/cog.png?width=461&height=461'};
function App() {
const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);
const buttons = {plus, done, exit, cog}
const [selected, setSelected] = useState(buttons.plus)
const [done, setDone] = useState(buttons.plus);
const openMenu = () => {
setSelected(buttons.exit);
//Make 'done' and 'cog' TouchableOpacity(s) visible. Click again and they become invisible.
//this.setState({ visible : !this.state.visible}) This makes visible invisible if not invisible already.
//visible should be the name of a state.
{/*handleAddTask();*/}
}
const handleAddTask = () => {
setDone(buttons.done);
Keyboard.dismiss();
setTaskItems([...taskItems, task]); {/*Puts out everything in the taskItems as a new array then appends the new task to it */}
setTask(null);
setSelected(buttons.plus) //Makes exit button go back to plus because it shows that its finished. DO same for display none for extended buttons when I figure it out.
}
const completeTask = (index) => {
let itemsCopy = [...taskItems];
itemsCopy.splice(index, 1);
setTaskItems(itemsCopy);
}
return (
<View style={styles.container}>
{/*Tasks*/}
<View style={styles.tasksWrapper}>
<Text style={styles.sectionTitle}>Tasks</Text>
<View style={styles.items}>
{/*This is where tasks go*/}
{
taskItems.map((item, index) => {
return (
<TouchableOpacity key={index} onPress={() => completeTask(index)}>
<Task text={item} />
</TouchableOpacity>
)
})
}
</View>
</View>
{/*Write a task*/}
<KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} style={styles.writeTaskWrapper}>
<TextInput style={styles.input} placeholder={'Write a task'} value={task} onChangeText={text => setTask(text)}/>
<View style={styles.buttonRow}>
<TouchableOpacity onPress={() => openConfig()}>
{/* Opens config for creation (i.e. calendar, timer, repetition, etc). */}
<View style={styles.addWrapper}>
<ImageBackground source={buttons.cog} alt='button' resizeMode="cover" style={styles.plusButton} />
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => handleAddTask()}>
{/* Done (check) button which does handleAddTask. */}
<View style={styles.addWrapper}>
<ImageBackground source={buttons.done} alt='button' resizeMode="cover" style={styles.plusButton} />
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => openMenu()}>
{/* Onpress opens menu, then shows exit button to go back and revert menu to one button. */}
<View style={styles.addWrapper}>
<ImageBackground source={selected} alt='button' resizeMode="cover" style={styles.plusButton} />
</View>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
</View>
);
}
The three touchable opacities at the bottom are what I'm trying to change. The first two should by default be invisible, and I think I can do that by assigning useState(false) for them and false should make their display none. Then on the click of the third touchable opacity, it changes their previous state => !previous state.
However, I'm not sure how to code this out and am quite confused. Any help is appreciated. Thanks!
This can be done using conditional rendering. You will either need a state for each of the buttons or a state that holds an array.
Here is a minimal example which works in general.
function App() {
const [isAVisible, setAVisible] = useState(true);
const [isBVisible, setBVisible] = useState(false);
return (
<View>
{isAVisible && (
<TouchableOpacity onPress={() => setIsBVisible(prev => !prev)}}>
<Text>Toggle Visibility of B</Text>
</TouchableOpacity>
)}
{isBVisible && (
<TouchableOpacity onPress={() => setIsAVisible(prev => !prev)}}>
<Text>Toggle Visibility of A</Text>
</TouchableOpacity>
)}
</View>
)
}
The above creates two TouchableOpacity. The first toggles the visibility of the second one, and the second one toggles the visibility of the first one. Notice, that the default state of the second one is set to false, thus it will be not be visible on first render.
Here whenever i click the icon it doesnt show anything. It supposed to be showing some text and when clicked again it should hide the text. Im using react native.
import React, { useState } from 'react';
import { View, Text, StyleSheet, Button, Image, TouchableOpacity} from 'react-native';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
export default function Edit(props, { navigation }) {
const [slide, setSlide] = useState(false);
const toggle = () => {
setSlide(!slide);
console.log('clicked');
return (
<View>
<Text>random</Text>
<Text>random</Text>
</View>
);
}
return (
<View>
<FontAwesome name="sliders" size={30} color="#000" onPress={() => toggle()}/>
</View>
}
After testing the only thing it shows is the console.log('clicked') message. It does not display anything else. Also the icon displays normally. Everything is working except the and the content in those tags.
Rather than returning the View from your toggle function, you actually need to display that view your view hierarchy (eg what is returned from your component).
I've demonstrated in the example by using a ternary expression -- if slide is true, it gets shown, otherwise it does not.
export default function Edit(props, { navigation }) {
const [slide, setSlide] = useState(false);
const toggle = () => {
setSlide(!slide);
console.log('clicked');
}
return (
<View>
<FontAwesome name="sliders" size={30} color="#000" onPress={() => toggle()}/>
{slide ? <View>
<Text>random</Text>
<Text>random</Text>
</View> : null}
</View>
);
}
Snack example: https://snack.expo.io/7lVezwWs7
Hi my custom component is wrapped in TouchableOpacity like this.
const profileOnClick = () => {
console.log('Card Clicked!');
};
export const InfluencerCard = props => {
const {influencer, navigation} = props;
return (
<TouchableOpacity onPress={() => profileOnClick()}>
<Card>
<Text>
{influencer.user.name}
</Text>
<Text>
{influencer.tags[0].name}
</Text>
</Card>
</TouchableOpacity>
);
};
In Homescreen
<ScrollView>
{data.categoriesForHome.map(category => (
<Layout key={category.id}>
<Text>
{category.name}({category.total})
</Text>
<ScrollView horizontal={true}>
{category.influencerProfiles.map(profile => (
<View key={profile.id}>
<InfluencerCard influencer={profile} />
</View>
))}
</ScrollView>
</Layout>
))}
</ScrollView>
When I clicked my custom component InfluencerCard, it doesn't do anything.
I wonder it is because that component is in other component, so parent component block clicking on custom component. Or calling onPress function is wrong.
But I tried without parent component, it was working.
What am I missing?
It was my mistake. The problem was not from code or components.
I use Card component from #ui-kitten/components and it implements TouchableOpacity behind the scene. So I don't need to wrap with TouchableOpacity again.So just do
<Card onPress={() => profileClick()}></Card>
I have a structure like this:
<View style={container}>
<View style={first}></View>
<View style={second}><View>
<View style={third}</View>
</View>
The container pretty much fills the whole screen.
When the user touches the container and moves the finger around without lifting the finger, I would like to know which View the finger is currently placed at.
Use TouchableWithoutFeedback to wrap around your views, and then you can call the onPressIn function to detect touch event.
You cannot detect the touched view unless and until you don't have any touch event on it.
To do that you can use TouchableOpacity (respond to the press and have visual feedback when touched.) or TouchableWithoutFeedback (it won't show any visual feedback when touched)
Below is the sample example as required:
import React, { Component } from 'react'
import {
TouchableOpacity,
View
} from 'react-native'
export default class SampleComponent extends Component {
constructor(props) {
super(props)
}
_onPressView = (viewName) => {
console.log("Tapped View ===> ", viewName)
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={() => this._onPressView("FirstView")}>
<View style={styles.first}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this._onPressView("SecondView")}>
<View style={styles.second}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this._onPressView("ThirdView")}>
<View style={styles.third}/>
</TouchableOpacity>
</View>
);
}
}