I've recently been learning React Native but haven't really found a way to manipulate the DOM.
I've been trying to make it so that if I click on the TouchableHighlight my Image moves down a couple of px, but I have not managed to get it to move yet and I honestly don't know how to go from here.
My onclick function works since it does return the log every time the button is clicked.
As of now I have this:
export default class MainBody extends Component {
onclick = () => {
console.log('On click works')
};
render() {
return (
<ScrollView showsHorizontalScrollIndicator={false} style={Style.horList} horizontal={true}>
<View >
{/*i need to move this Image down!*/}
<Image source={require("./img/example.png")}/>
<View>
<Text style={Style.peopleInvited}>This is text</Text>
</View>
{/*When clicked on this touchable highlight!*/}
<TouchableHighlight onPress={this.onclick}}>
<Image source={require('./img/moveImg.png')}/>
</TouchableHighlight>
</View>
</ScrollView>
}
If someone could help me get past this that would be greatly appreciated.
Thank you so much for your time!
There are many ways to do this, but perhaps the easiest way would be using states.
class MainBody extends Component {
constructor(props) {
super(props);
this.state = {
top: 0 // Initial value
};
}
onclick = () => {
console.log('On click works')
this.setState( { top: this.state.top + 5 }) // 5 is value of change.
};
render() {
return (
<ScrollView showsHorizontalScrollIndicator={false} horizontal={true}>
<View >
{/*i need to move this Image down!*/}
<Image style={{top: this.state.top}}source={require("./img/example.png")}/>
<View>
<Text>This is text</Text>
</View>
{/*When clicked on this touchable highlight!*/}
<TouchableHighlight onPress={this.onclick}>
<Image source={require("./img/moveImg.png")}/>
</TouchableHighlight>
</View>
</ScrollView>
);
}
}
Related
I am trying to show or print the duration (timer) when the button start is pressed, but nothing is showing after pressing start. I tried doing Button instead of TouchableOpacity, but still, nothing changed.
class Timer extends Component {
constructor(props){
super(props)
this.state = {
count: 0
}
}
render () {
const {count} = this.state
return (
<ScrollView>
<SafeAreaView style={styles.container}>
<View style={styles.textInputContainer}>
<Text style={styles.txtHello}>Press start when ready</Text>
<View style={styles.sep}>
</View>
<TouchableOpacity style={styles.button}
onPress={ () =>
<View style={styles.textInputContainer}>
<Text>
<h2> Duration: {count}</h2>
</Text>
</View>
}
>
<Text>start</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
</ScrollView>
)
}
componentDidMount(){
this.myInterval = setInterval(()=>{
this.setState({
count: this.state.count + 1
})
}, 1000)
}
}
I don't think this is a right way to do it in React. What you would like to do is set a isVisible state, change it with your onPress props in Button/TouchableOpacity and finally conditionally show the view you want to display based on that isVisible variable. Something like this:
class Timer extends Component {
constructor(props){
super(props)
this.state = {
isVisisble:false;
}
}
render(){
return(
<View>
<TouchableOpacity
onPress={ () => this.setState((prevState)=>{isVisible:!prevState.isVisible})}
>
<Text>start</Text>
</TouchableOpacity>
{this.state.isVisible && <View></View>} <- Conditional View here
</View>
)}
Hey there so i'm new to react native and javascript and currently i'm learning to make a custom radio button with images it looks like this my custom radio button in this page user is going to pick one button from the list, and i want to make it when the page first render it will show one pressed button and user is only allowed to pick one button. Can anyone tell me how to figure this out? Thanks in advance
here are my codes
RadioButton.js
export default class RadioButton extends Component {
constructor(props) {
super(props);
this.state = {
selected: this.props.currentSelection === this.props.value,
}
}
button() {
var imgSource = this.state.selected? this.props.normalImg : this.props.selectedImg;
return (
<Image
source={ imgSource }
/>
);
}
render() {
let activeButton = this.props.activeStyle ? this.props.activeStyle : styles.activeButton;
return (
<View style={[styles.container, this.props.containerStyle, this.state.selected || this.props.normalImg ? activeButton : inactiveButton]}>
<TouchableOpacity onPress={() => {
this.setState({ selected: !this.state.selected });
}}>
{
this.button()
}
</TouchableOpacity>
</View>
);
}
}
ActivityLog.js
class ActivityLog extends Component {
constructor(props){
super(props);
}
render() {
return (
<View style={styles.innerContainer}>
<Text style={styles.dialogText}>{`Log my activity at ${time} as...`}</Text>
<View style={styles.buttonContainer}>
<RadioButton selectedImg={img.activity.breakA} normalImg={img.activity.break} containerStyle={{marginHorizontal: normalize(10)}}/>
<RadioButton selectedImg={img.activity.meetingA} normalImg={img.activity.meeting} containerStyle={{marginHorizontal: normalize(10)}}/>
</View>
<View style={styles.buttonContainer}>
<RadioButton selectedImg={img.activity.otwA} normalImg={img.activity.otw} containerStyle={{marginHorizontal: normalize(10)}}/>
<RadioButton selectedImg={img.activity.officeA} normalImg={img.activity.office} containerStyle={{marginHorizontal: normalize(10)}}/>
</View>
);
}
}
Extract the activeStatus to ActivityLog so as to track which button is selected,right now you are maintaing a state for every button as a local state.So it is difficult to know other components to know about the button's active status.
Here is a generic implementation for rough idea.
const Child=(props)=>{
<TouchableOpacity onPress={props.handlePress}>
<Text style={[baseStyle,active && activeStyle]}>{props.title}</Text>
</TouchableOpacity>
}
class Parent extends React.Component{
state={
selectedChild:''
}
changeSelection=(sometitle)=>{
this.setState({
selectedChild:sometitle
})
}
render(){
return(
<View>
<Child handlePress={()=>this.changeSelection('1')} active={this.state.selectedChild==='1'}/>
<Child handlePress={()=>this.changeSelection('2')} active={this.state.selectedChild==='2'}/>
<Child handlePress={()=>this.changeSelection('3')} active={this.state.selectedChild==='3'}/>
<Child handlePress={()=>this.changeSelection('4')} active={this.state.selectedChild==='4'}/>
</View>
)
}
}
Expo demo Link
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>
);
}
}
I currently have two buttons (No, Yes)( component imported from native-base package) that when pressed should update the state with either 0 or 1 respectively and also toggle between true or false to notify if this field has been filled (by default, neither of the two will be pressed, hence set to false).
I have a handleOnClick() function bound to the "No" button with a debugger to test if I actually do hit it, but once inside this function, I'm not sure how to grab any info for associated components (i.e. the "No" text within the Text component) so I can perform logic to check if "No" or "Yes" was pressed.
If this was done in pure React, I know I can access certain data attributes that I add to DOM elements or traverse the DOM, but I'm not sure how to do this in React Native or if I'm able to add custom props to a built in component that I can then access.
class Toggle extends Component {
constructor() {
super()
this.state = {
selectedOption: '',
isFilled: false
}
this.checkField = this.checkField.bind(this)
this.handleOnClick = this.handleOnClick.bind(this)
}
checkField() {
console.log(this)
// debugger
}
handleOnClick(ev) {
debugger
console.log("I was pressed")
}
render() {
const options = this.props.inputInfo.options //=> [0,1]
const optionLabels = this.props.inputInfo.options_labels_en //=>["No","Yes"]
return (
<View style={{flexDirection: 'row'}}>
<View style={styles.row} >
<Button light full onPress={this.handleOnClick}><Text>No</Text></Button>
</View>
<View style={styles.row} >
<Button success full><Text>Yes</Text></Button>
</View>
</View>
)
}
}
If you want to pass information into function, you can pass it when it is called. In your case, you can call your function from arrow function, like so:
<View style={{flexDirection: 'row'}}>
<View style={styles.row} >
<Button light full onPress={() => this.handleOnClick('No')}>
<Text>No</Text>
</Button>
</View>
<View style={styles.row} >
<Button success full><Text>Yes</Text></Button>
</View>
</View>
And in your function
handleOnClick(text) {
debugger
console.log(`${text} pressed`)
}
Have you tried:
render() {
const options = this.props.inputInfo.options //=> [0,1]
const optionLabels = this.props.inputInfo.options_labels_en //=>["No","Yes"]
return (
<View style={{flexDirection: 'row'}}>
<View style={styles.row} >
<Button light full onPress={() => this.handleOnClick('No')}><Text>No</Text></Button>
</View>
<View style={styles.row} >
<Button success full onPress={() => this.handleOnClick('Yes')}><Text>Yes</Text></Button>
</View>
</View>
)
}
and
handleOnClick(word) {
this.setState({ selectedOption: word, isFilled: true })
}
I've written a click handler to resolve a download button to the google play store URL.
The problem is that when the page loads, the URL is immediately visited.
The click handler is nested inside an onPress attribute, and I don't press anything, so I'm struggling to understand why this would be happening.
Any help would be appreciated!
OpenURL.js:
'use strict';
import React, {
Component,
PropTypes,
Linking,
StyleSheet,
Text,
TouchableNativeFeedback,
TouchableHighlight,
View
} from 'react-native';
class OpenURLButton extends Component {
constructor(props) {
super(props);
}
handleClick(url) {
console.log(url);
console.log('handling click! this is : ');
console.dir(this);
Linking.canOpenURL(this.props.url).then(supported => {
if (supported) {
Linking.openURL(this.props.url);
} else {
console.log('Don\'t know how to open URI: ' + this.props.url);
}
});
}
render() {
console.log('logging "this" inside render inside OpenURL.js:');
console.dir(this);
return (
<TouchableHighlight onPress={this.handleClick(this.props.appStoreUrl)}>
<Text>Download {this.props.appStoreUrl}</Text>
</TouchableHighlight>
);
}
}
OpenURLButton.propTypes = {
url: React.PropTypes.string,
}
export default OpenURLButton;
Inventory.js:
<ScrollView>
<View style={styles.ImageContainer}>
<Image style={styles.ImageBanner} source={{uri: selectedInventory.bannerImage}} />
</View>
<View style={styles.ListGridItemCaption}>
<Image style={[styles.ImageThumb, styles.ImageGridThumb]} source={{uri: selectedInventory.thumbImage}} />
<Text style={styles.Text} key="header">{name}</Text>
</View>
<View>
<Text>{selectedInventory.description}</Text>
<OpenURLButton url={selectedInventory.appStoreUrl}/>
</View>
</ScrollView>
Change:
<TouchableHighlight onPress={this.handleClick(this.props.appStoreUrl)}>
<Text>Download {this.props.appStoreUrl}</Text>
</TouchableHighlight>
To:
<TouchableHighlight onPress={() => {this.handleClick(this.props.appStoreUrl)}}>
<Text>Download {this.props.appStoreUrl}</Text>
</TouchableHighlight>
With the change you are creating anonymous function that are calling on "your" method. This will work.