So I've created a custom component in React Native, which just wraps a TouchableOpacity and turns it into a nice button component. Though when I use an animated version of the component (through createAnimatedComponent) it does not move, anyone know why?
const AnimatedMainButton = Animated.createAnimatedComponent(MainButton);
...
render() {
return <AnimatedMainButton style={{transform: [{translateX: 100}]}} />
}
...
import React, { Component } from 'react';
import {
Text,
View,
StyleSheet,
TouchableOpacity,
} from 'react-native';
export default class MainButton extends Component {
static propTypes = {
title: React.PropTypes.string.isRequired,
onPress: React.PropTypes.func.isRequired,
color: React.PropTypes.string,
textColor: React.PropTypes.string,
};
static defaultProps = {
color: '#FFFFFF',
textColor: '#000000',
};
render() {
const { title, onPress, color, textColor } = this.props;
return (
<TouchableOpacity style={[styles.mainbutton, {backgroundColor: color}]} onPress={onPress}>
<Text style={[styles.mainbuttontext, {color: textColor}]}>{title}</Text>
</TouchableOpacity>
)
}
}
const styles = StyleSheet.create({
mainbutton: {
width: '80%',
height: 60,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 10,
shadowColor: '#000000',
shadowOffset: { width: 0, height: 10 },
shadowOpacity: 0.8,
shadowRadius: 20,
elevation: 5,
},
mainbuttontext: {
fontSize: 40,
fontFamily: 'DroidSerif',
},
});
You need to pass down the style to the elements contained within the custom component. duh! Otherwise any transformations done by AnimatedComponent, or parents of, won't reach the native base components.
return (
<TouchableOpacity style={[this.props.style, ...
Related
I'm trying to generate a component with a search bar inside a view and a couple of buttons inside other view. Something like this:
Expected
I develop this piece of code but I'm not able to do this parallel view.
import React from "react";
import { StyleSheet, View, FlatList, Image, Text, Item } from "react-native";
import { colorUtil } from "../../constants/Colours";
import { SearchBar, Button } from 'react-native-elements';
export default class App extends React.Component {
state = {
search: '',
};
updateSearch = search => {
this.setState({ search });
};
render() {
const { search } = this.state;
const styles = StyleSheet.create({
searchBarContainer: {
borderBottomWidth: 1,
borderBottomColor: '#e2e2e2',
height: 64,
backgroundColor: '#FFFFFF'
},
searchBarField: {
position: 'relative',
margin: 0,
width: '48%',
//padding: 44,
//fontSize: 14,
borderRadius: 80,
backgroundColor: '#E5E7E8'
},
btnField: {
borderBottomWidth: 1,
borderBottomColor: '#e2e2e2',
height: 64,
backgroundColor: '#FFFFFF'
}
});
return (
<View style={styles.searchBarContainer}>
<View style={styles.searchBarField}>
<SearchBar
lightTheme
onChangeText={this.updateSearch}
onClearText={this.updateSearch}
value={search}
icon={{ type: 'font-awesome', name: 'search' }}
placeholder='Find' />
</View>
<View style={styles.btnField}>
<Button
title="Solid Button"
/>
</View>
</View>
);
}
}
But the result is not equal to. How can I make this fields parallel?
You have to set the flex direction of parent view to row to place everything in the same line.
Also removing the height property will align the content properly.
searchBarContainer: {
borderBottomWidth: 1,
borderBottomColor: '#e2e2e2',
height: 64,
backgroundColor: '#FFFFFF',
flexDirection: 'row',
alignItems: 'center',
},
btnField: {
borderBottomWidth: 1,
borderBottomColor: '#e2e2e2',
backgroundColor: '#FFFFFF',
},
On web, shaping a TouchableOpacity makes it so only the shape is clickable, however on mobile the entire "box" surrounding the shape is clickable. Is there any way at all to make it so just the shape is clickable?
I have tried shaping the view and setting the style on both View and TouchableOpacity to overflow: 'hidden' but this also fails to contain the area which is touchable.
import React, { Component } from 'react';
import { StyleSheet, TouchableOpacity, Text, View } from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
onPress = () => {
this.setState({
count: this.state.count + 1,
});
};
render() {
return (
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={this.onPress}>
<Text> Touch Here </Text>
</TouchableOpacity>
<View style={[styles.countContainer]}>
<Text style={[styles.countText]}>
{this.state.count !== 0 ? this.state.count : null}
</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingHorizontal: 10,
overflow: 'hidden',
},
button: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
borderRadius: 640,
height: 320,
width: 320,
overflow: 'hidden',
},
countContainer: {
alignItems: 'center',
padding: 10,
},
countText: {
color: '#FF00FF',
},
});
Here's a snack example of my problem
I have a little problem with an app that I am working on. I have to make something like a note app. There for I have a button that navigates me to another screen where I can write the note and I have a save button that should send me back to the previews screen and the scrollview shold be updated
Here is what I've tried so far:
App.js:
import React, { Component } from 'react';
import Main from './app/components/Main.js';
import NoteBody from './app/components/NoteBody.js';
import {StackNavigator} from 'react-navigation'
const App = StackNavigator({Home: {screen: Main}, WriteNote: {screen: NoteBody}});
export default App;
Main.js:
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TextInput,
ScrollView,
TouchableOpacity,
AsyncStorage,
} from 'react-native';
import Note from './Note';
import NoteBody from './NoteBody.js';
export default class Main extends Component {
static navigationOptions = {
title: 'Notes',
};
constructor(props){
super(props);
this.state = {
noteArray: [],
noteText: '',
};
}
componentDidMount(){
this.getSavedNotes(this.state.noteArray);
}
render() {
let notes = this.state.noteArray.map((val, key)=>{
return <Note key={key} keyval={key} val={val}
deleteMethod={()=>this.deleteNote(key)}/>
});
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<ScrollView style={styles.scrollViewContainer}>
<ScrollView style={styles.scrollContainer}>
{notes}
</ScrollView>
<TouchableOpacity onPress={() =>
navigate('WriteNote' ,{onNavigateBack:
this.handleOnNavigateBack.bind(this)})}
style={styles.addButton}>
<Text style={styles.addButtonText}>+</Text>
<Text style={styles.addButtonAditionalText}>Add note</Text>
</TouchableOpacity>
</ScrollView>
</View>
);
}
deleteNote(key){
this.state.noteArray.splice(key, 1);
this.setState({noteArray: this.state.noteArray});
AsyncStorage.setItem('arr', JSON.stringify(this.state.noteArray));
// alert(this.state.noteArray);
}
getSavedNotes = async (noteArray) =>{
try{
let data = await AsyncStorage.getItem('arr');
if(JSON.parse(data))
{
this.setState({noteArray: JSON.parse(data)});
}
}catch(error){
alert(error);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
scrollContainer: {
flex: 1,
},
addButton: {
position: 'relative',
zIndex: 11,
left: 0,
top: 0,
alignItems: 'flex-start',
justifyContent: 'flex-end',
width: 100,
height: 60,
elevation: 8
},
addButtonText: {
color: '#000',
fontSize: 60,
},
addButtonAditionalText: {
color: '#000',
fontSize: 12,
marginLeft: 40,
position: 'absolute',
bottom: 20,
},
scrollViewContainer: {
flex: 1,
marginBottom: 70,
}
});
Note.js: Here we have the scrollview and the button that navigates you to the NoteBody screen.
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
} from 'react-native';
export default class Note extends Component {
render() {
return (
<View key={this.props.keyval} style={styles.note}>
<Text style={styles.noteText}>{this.props.val.date}</Text>
<Text style={styles.noteText}>{this.props.val.note}</Text>
<TouchableOpacity onPress={this.props.deleteMethod} style={styles.noteDelete}>
<Text style={styles.noteDeleteText}>Del</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
note: {
position: 'relative',
padding: 20,
paddingRight: 100,
borderBottomWidth:2,
borderBottomColor: '#ededed'
},
noteText: {
paddingLeft: 20,
borderLeftWidth: 10,
borderLeftColor: '#0000FF'
},
noteDelete: {
position: 'absolute',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#2980b9',
padding: 10,
top: 10,
bottom: 10,
right: 10
},
noteDeleteText: {
color: 'white'
}
});
and finally NoteBody: Here is where you can write the body of the note and you have that save button that should also save the data in an AsyncStorage so I can display it even after the app is closed.
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TextInput,
TouchableOpacity,
AsyncStorage,
} from 'react-native';
import Note from './Note.js';
export default class NoteBody extends Component {
static navigationOptions = {
title: 'Note',
};
constructor(props){
super(props);
this.state = {
noteArray: [],
noteText: '',
};
}
componentDidMount(){
this.getSavedNotes(this.state.noteArray);
}
render() {
let notes = this.state.noteArray.map((val, key)=>{
return <Note key={key} keyval={key} val={val}
deleteMethod={()=>this.deleteNote(key)}/>
});
return (
<View style={styles.container}>
<View style={styles.noteBody}>
<TextInput
multiline = {true}
numberOfLines = {1000000}
style={styles.textInput}
placeholder='Write your note here'
onChangeText={(noteText)=> this.setState({noteText})}
value={this.state.noteText}
placeholderTextColor='grey'
underlineColorAndroid='transparent'>
</TextInput>
</View>
<TouchableOpacity onPress={ this.addNote.bind(this) } style={styles.addButton}>
<Text style={styles.addButtonText}>SAVE</Text>
</TouchableOpacity>
</View>
);
}
addNote(){
const { navigate } = this.props.navigation;
if(this.state.noteText){
var d = new Date();
this.state.noteArray.push({
'date':d.getFullYear()+
"/"+(d.getMonth()+1) +
"/"+ d.getDate(),
'note': this.state.noteText
});
this.setState({ noteArray: this.state.noteArray });
this.setState({noteText:''});
AsyncStorage.setItem('arr', JSON.stringify(this.state.noteArray));
this.props.navigation.state.params.onNavigateBack();
navigate('Home');
// alert(this.state.noteArray);
}
}
getSavedNotes = async (noteArray) =>{
try{
let data = await AsyncStorage.getItem('arr');
if(JSON.parse(data))
{
this.setState({noteArray: JSON.parse(data)});
}
}catch(error){
alert(error);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
noteBody:{
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
zIndex: 10,
alignItems: 'center',
borderBottomWidth:1,
borderTopColor: '#000',
marginBottom: 100,
},
textInput: {
alignSelf: 'stretch',
textAlignVertical: 'top',
backgroundColor: '#fff',
color: '#000',
padding: 20,
borderTopWidth:2,
borderTopColor: '#ededed',
},
addButton: {
position: 'absolute',
zIndex: 11,
left: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center',
width: 300,
backgroundColor: '#00FF00',
height: 60,
elevation: 8
},
addButtonText: {
color: '#fff',
fontSize: 24,
},
});
The save button only saves the last note I wrote and it doesn't even show it on the scrollview immediately. I have to reopen the app to display it.
There are a couple of things which are wrong here:
First you only fetch the saved notes in the constructor of your Main component, which only gets called on instantiation. The recommended place to put this code is in componentDidMount(). Also I don't understand why you are are passing the noteArray state to your getSavedNotes() method.
Next, and this is an important one: your methods to add and delete notes from the array are mutating (splice and push). Since React uses shallow comparison to determine when to re-render, you need to create a new object when using setState(). So for additions you could use concat() and for deletions the omit() function of Lodash is very useful. Alternatively you could use the spread operator.
Disclaimer: I haven't yet read all of your code in detail, so there might still be some additional problems.
Edit: with FlatList
// render() method of Main.js
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<ScrollView style={styles.scrollViewContainer}>
<ScrollView style={styles.scrollContainer}>
<FlatList
data={this.state.noteArray}
renderItem={({item, index}) => this.renderItem(item, index)}
keyExtractor={(item, index) => `${index}`}
/>
</ScrollView>
<TouchableOpacity onPress={() =>
navigate('WriteNote')}
style={styles.addButton}>
<Text style={styles.addButtonText}>+</Text>
<Text style={styles.addButtonAditionalText}>Add note</Text>
</TouchableOpacity>
</ScrollView>
</View>
);
}
renderItem = (item, index) => {
return (
<Note
keyval={index}
val={item}
deleteMethod={()=>this.deleteNote(index)}
/>
);
}
It looks like you could add a listener in Main.js for 'onFocus' events. I would use the callback to query AsyncStorage and set state with the result.
Screen A
Method to do the thing in Screen A that you want to happen when navigating back from Screen B:
handleOnNavigateBack = (foo) => {
this.setState({
foo
})
}
This is the React Navigation method in Screen A to navigate to Screen B:
this.props.navigation.navigate('ScreenB', {
onNavigateBack: this.handleOnNavigateBack})
…or if your handleOnNavigateBack function is not a arrow function (which binds this) you'll need to bind this: (ht #stanica)
this.props.navigation.navigate('ScreenB', {
onNavigateBack: this.handleOnNavigateBack.bind(this)
})
Screen B
After navigating to Screen B and ready to Navigate back to Screen A…
Call the function (passed to Screen B from Screen A) to do the thing in Screen A:
this.props.navigation.state.params.onNavigateBack(this.state.foo)
Then call the React Navigation method to go Back (to Screen A):
this.props.navigation.goBack()
I also updated my question's code so it is the version that dose what is suppose to do.
Because of the many layers displayed on my form and to create transparency effects, I need to place my ScrollView at an absolute position; unfortunately, when add the { position: 'absolute' } style, my ScrollView snaps back to the top after I release my finger.
I read all the relevant threads on stackoverflow to no avail.
Here's a screen capture of the code below: http://imgur.com/a/fd4ad
Here's the code I am using:
import React, { Component } from 'react';
import { View, ScrollView, Text } from 'react-native';
class HomeTest extends Component {
render() {
const { headerTextStyle, homeView, scrollViewStyle, textStyle } = styles;
return (
<View>
<ScrollView style={scrollViewStyle} contentContainerStyle={homeView}>
<Text style={textStyle}>I'd love to figure out why this is not working.........................</Text>
</ScrollView>
<Text style={headerTextStyle}>Header</Text>
</View>
);
}
}
const styles = {
headerTextStyle: {
fontSize: 40,
alignSelf: 'center'
},
scrollViewStyle: {
position: 'absolute',
paddingTop: 60,
marginTop: 0
},
homeView: {
alignItems: 'center',
justifyContent: 'center'
},
textStyle: {
fontSize: 96
},
};
export default HomeTest;
Solution found on GitHub: https://github.com/facebook/react-native/issues/5438
Alright, the secret was to add the following styling components: (I'll have to figure out why - and post it - later and brush up my CSS skills)
Add styling to the parent view (position: relative, flex: 1)
Add new styling properties to the scroll view (top, bottom, left, right)
Here's the updated code:
import React, { Component } from 'react';
import { View, ScrollView, Text } from 'react-native';
class HomeTest extends Component {
render() {
const { headerTextStyle, homeView, scrollViewStyle, textStyle, mainView } = styles;
return (
<View style={mainView}>
<ScrollView style={scrollViewStyle} contentContainerStyle={homeView}>
<Text style={textStyle}>I'd love to figure out why this is not working.........................</Text>
</ScrollView>
<Text style={headerTextStyle}>Header</Text>
</View>
);
}
}
const styles = {
headerTextStyle: {
fontSize: 40,
alignSelf: 'center'
},
scrollViewStyle: {
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
paddingTop: 60
},
homeView: {
alignItems: 'center',
justifyContent: 'center'
},
textStyle: {
fontSize: 96
},
mainView: {
flex: 1,
position: 'relative'
}
};
export default HomeTest;
You just need to specify the height of scrollView
scrollViewStyle: {
position: 'absolute',
paddingTop: 60,
marginTop: 0 ,
height: 300 // <----
},
I am new to react-native. In my app, I'm using a switch and changing the tint color to differentiate ON and OFF, but my actual requirement is to show "YES" or "NO" text inside the switch like below.
Here is my Code:
<Switch
onValueChange={this.change.bind(this)}
style={{marginBottom:10,width:90,marginRight:6,marginLeft:6}}
value={true}
thumbTintColor="#0000ff"
tintColor="#ff0000"
/>
Please give me suggestions to solve this issue, Any help much appreciated.
Finally I got the On off inside switch .......
install
npm install --save react-native-switch
import { Switch } from 'react-native-switch';
<Switch
value={true}
onValueChange={(val) => console.log(val)}
disabled={false}
activeText={'On'}
inActiveText={'Off'}
backgroundActive={'green'}
backgroundInactive={'gray'}
circleActiveColor={'#30a566'}
circleInActiveColor={'#000000'}/>
Refer this link...
https://github.com/shahen94/react-native-switch
I would start with something like this and then iterate and polish until it fulfills the requirements and looks good. This isn't a complete solution but should give you some ideas.
import React from 'react';
import { LayoutAnimation, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
const styles = StyleSheet.create({
container: {
width: 80,
height: 30,
backgroundColor: 'grey',
flexDirection: 'row',
overflow: 'visible',
borderRadius: 15,
shadowColor: 'black',
shadowOpacity: 1.0,
shadowOffset: {
width: -2,
height: 2,
},
},
circle: {
width: 34,
height: 34,
borderRadius: 17,
backgroundColor: 'white',
marginTop: -2,
shadowColor: 'black',
shadowOpacity: 1.0,
shadowOffset: {
width: 2,
height: 2,
},
},
activeContainer: {
backgroundColor: 'blue',
flexDirection: 'row-reverse',
},
label: {
alignSelf: 'center',
backgroundColor: 'transparent',
paddingHorizontal: 6,
fontWeight: 'bold',
},
});
class LabeledSwitch extends React.Component {
constructor(props) {
super(props);
this.state = {
value: props.value,
};
this.toggle = this.toggle.bind(this);
}
componentWillReceiveProps(nextProps) {
// update local state.value if props.value changes....
if (nextProps.value !== this.state.value) {
this.setState({ value: nextProps.value });
}
}
toggle() {
// define how we will use LayoutAnimation to give smooth transition between state change
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
const newValue = !this.state.value;
this.setState({
value: newValue,
});
// fire function if exists
if (typeof this.props.onValueChange === 'function') {
this.props.onValueChange(newValue);
}
}
render() {
const { value } = this.state;
return (
<TouchableOpacity onPress={this.toggle}>
<View style={[
styles.container,
value && styles.activeContainer]}
>
<View style={styles.circle} />
<Text style={styles.label}>
{ value ? 'YES' : 'NO' }
</Text>
</View>
</TouchableOpacity>
);
}
}
LabeledSwitch.propTypes = {
onValueChange: React.PropTypes.func,
value: React.PropTypes.bool,
};
LabeledSwitch.defaultProps = {
};
export default LabeledSwitch;