How to pass a variable on the transform property style in react-native? - react-native

I try to pass a variable on the transform property style in react-native but it don't work. My code bellow :
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';
import { Accelerometer, Gyroscope } from 'react-native-sensors';
import { sensors } from 'react-native-sensors';
export default class Sensors extends Component {
constructor(props) {
super(props);
this.state = {
rotate: 0
}
}
render() {
var degree = this.state.rotate;
return (
<View style={styles.container}>
<View style={styles.fleche}></View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
fleche: {
width: 5,
height: 150,
backgroundColor: '#000000',
borderRadius: 5,
transform: [{ rotate: '' + this.state.rotate + 'deg' }],
}
});
AppRegistry.registerComponent('Compass', () => Sensors);
I don't know the way to pass the variable in the transform style. Currently, I have this error : undefine is not an object(evaluating 'this.state.rotate').

Try this:
render(){
const transform = [{ rotate: this.state.rotate + 'deg' }]
var degree = this.state.rotate
return (
<View style={styles.container}>
<View style={[styles.fleche, transform]} />
</View>
)
}

Related

FlatList not rendering row

I am trying to learn FlatList component of react-native. Observing a tutorial, I have implemented a sample applications which list components inside a scrollview. I am trying to replace scrollview with FlatList, but items are not renderings on the screen. I have included the main source code here.
App.js
import React, { Component } from 'react'
import {
StyleSheet,
View,
ScrollView,
FlatList
} from 'react-native'
import ColorButton from './components/ColorButton'
class App extends Component {
constructor() {
super()
this.state = {
backgroundColor: 'blue'
}
this.changeColor = this.changeColor.bind(this)
}
changeColor(backgroundColor) {
this.setState({backgroundColor})
}
render() {
const { backgroundColor } = this.state
return(
<FlatList
data = {'red', 'green', 'salmon'}
renderItem = {(color) => {
<ColorButton backgroundColor={color} onSelect={this.changeColor}></ColorButton>
} } />
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 20
}
})
export default App
ColorButton.js
import React from 'react'
import {
StyleSheet,
Text,
View,
TouchableHighlight
} from 'react-native'
const ColorButton = ({ backgroundColor, onSelect=f=>f }) => (
<TouchableHighlight
style = {styles.button}
onPress={() => onSelect(backgroundColor)}
underlayColor="orange">
<View style = {styles.row}>
<View style = {[styles.sample, {backgroundColor}]} />
<Text style = {styles.text}>backgroundColor</Text>
</View>
</TouchableHighlight>
)
const styles = StyleSheet.create({
button: {
margin: 10,
padding: 10,
borderWidth: 2,
borderRadius: 10,
alignSelf: 'stretch',
backgroundColor: 'rgba(255,255,255,0.8)'
},
row: {
flexDirection: 'row',
alignItems: 'center'
},
sample: {
height: 20,
width: 20,
borderRadius: 10,
margin: 5,
backgroundColor: 'white'
},
text: {
fontSize: 30,
margin: 5
}
})
export default ColorButton
Change your code for flatlist to the one below :
<FlatList
data = {['red', 'green', 'salmon']}
renderItem = {({item}) => {
<ColorButton backgroundColor={item} onSelect={this.changeColor}>
</ColorButton>
} } />
Hope it helps. feel free for doubts

React native SectionList not updating

I am developing a sample app as part of learning react-native, in which it has a ColorForm that accepts the value from a TextInput and with the help of Props, the data will be sent to the Main view, such as App. The App has a SectionList that doesn't update with the new value inputs from ColorForm.
Following is the source code that I have used:
App.js
import React, { Component } from 'react'
import {
StyleSheet,
SectionList,
Text,
Alert
} from 'react-native'
import ColorButton from './components/ColorButton'
import ColorForm from './components/ColorForm'
class App extends Component {
constructor() {
super()
this.state = {
backgroundColor: 'blue',
availableColors: ['red', 'green', 'yellow', 'pink']
}
this.changeColor = this.changeColor.bind(this)
this.newColor = this.newColor.bind(this)
}
changeColor(backgroundColor) {
this.setState({ backgroundColor })
}
newColor(color) {
const colors = [
...this.state.availableColors,
color
]
this.setState(colors)
}
render() {
const { backgroundColor, availableColors } = this.state
return (
<SectionList style={styles.list}
backgroundColor={backgroundColor}
sections={[{ title: "Header", data: availableColors }]}
renderSectionHeader={({ section }) => (
<ColorForm onNewColor={this.newColor} />
)}
renderItem={({ item }) => (
<ColorButton backgroundColor={item} onSelect={this.changeColor} />
)}
keyExtractor={(item, index) => index}
/>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 20
},
list: {
marginTop: 40
}
})
export default App
ColorForm.js
import React, { Component } from 'react'
import {
View,
Text,
StyleSheet,
TextInput
} from 'react-native'
import PropTypes from 'prop-types'
export default class ColorForm extends Component {
constructor() {
super()
this.state = {
txtColor: ''
}
this.submit = this.submit.bind(this)
}
submit() {
this.props.onNewColor(this.state.txtColor.toLowerCase())
this.setState({ txtColor: '' })
}
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.txtInput}
placeholder="Enter a color..."
onChangeText={(txtColor) => this.setState({ txtColor })}
value={this.state.txtColor}
/>
<Text style={styles.button} onPress={this.submit}>Add</Text>
</View>
)
}
}
ColorForm.propTypes = {
onNewColor: PropTypes.func.isRequired
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-around',
backgroundColor: 'lightgrey',
height: 70,
paddingTop: 20
},
txtInput: {
flex: 1,
margin: 5,
padding: 5,
borderWidth: 2,
fontSize: 20,
borderRadius: 5,
backgroundColor: 'snow'
},
button: {
backgroundColor: 'darkblue',
margin: 5,
padding: 5,
alignItems: 'center',
justifyContent: 'center',
color: 'white',
fontSize: 20
}
})
Can anyone help me to sort out the issue? Thanks in advance.
It looks like the state is not being updated in your method newColor, since availableColors is an array u can use push operation to add new value to the array update the code as below and it will work.
newColor(color) {
console.log('adding', color)
const colors = this.state.availableColors
colors.push(color)
this.setState(colors)
}

React-Native Constructor

Please help me find what is wrong in the following React-Native code?
It says after constructor (props) should have ';' semicolon. I don't know if I declared it in the right way.
import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';
export default function App() {
constructor (props){
this.state = {
text: 'HI'
}
}
render () {
return (
<View style={styles.container}>
<TextInput style={styles.input}
placeholder = 'Enter Value...'
placeholderTextColor ='#E74292'
onChangeText = {(text) => {
this.setState({text})
}}
/>
</View>
);
}
const styles = StyleSheet.create({
container:{
flex:1,
backgroundColor:'#F4C724',
},
input :{
marginTop:30,
height:30,
width:30,
borderWidth:2,
padding:10,
borderRadius: 5,
borderColor:'#1287A5'
}
}
);
You should declare the component as class instead of function if you want a constructor:
import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';
export default class App {
constructor(props) {
this.state = {
text: 'HI'
};
}
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Enter Value..."
placeholderTextColor="#E74292"
onChangeText={text => {
this.setState({ text });
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F4C724'
},
input: {
marginTop: 30,
height: 30,
width: 30,
borderWidth: 2,
padding: 10,
borderRadius: 5,
borderColor: '#1287A5'
}
});
constructor only works in class based component so switch to class based component rather than . functional whihc is now.
import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';
export default class App extends React.Component{
constructor(props) {
this.state = {
text: 'HI'
};
}
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Enter Value..."
placeholderTextColor="#E74292"
onChangeText={text => {
this.setState({ text });
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F4C724'
},
input: {
marginTop: 30,
height: 30,
width: 30,
borderWidth: 2,
padding: 10,
borderRadius: 5,
borderColor: '#1287A5'
}
});
You need to study the difference between functional and class component.
Functional component is just a plain java-script function which also known as stateless component. They do not manage their own state or have access to the lifecycle methods.
for more please follow the link below:
https://medium.com/#Zwenza/functional-vs-class-components-in-react-231e3fbd7108
you can use useState , the dynamic function value loads to the initial variable on load
import React,{ useState } from 'react';
import { View, Text, Button, ImageBackground} from 'react-native';
export default function Home({navigation}){
//function getversion onload
const [initval,setInitval] = useState(()=>{ return '123456'});
return(
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text> {initval} </Text>
</View>
);
}
You cannot have a constructor() in functional components. You should either change function component to class component or go and check out the react doc about React Hooks. You are going to have a better understanding of the differences between react class components and react functional components.

how to expand a component on click to full screen width and height with animation in reactnative

I have tried to implement the component expand to full screen in react native by using Layout animation in react-native but it was not good to look. Can any one help me in getting it?
changeLayout = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
this.setState({ expanded: !this.state.expanded });
};
I expect to expand the component on click to full screen and again collapse it on click.
Set the initial value you want through the animation, obtain the screen width and height, and create a click function to execute.
This is an example that I made. Click this link if you want to run it yourself.
import React from 'react';
import { Animated, Text, View,Dimensions,Button } from 'react-native';
const screenwidth = Dimensions.get('screen').width
const screenheight = Dimensions.get('screen').height
class FadeInView extends React.Component {
state = {
fadeAnim: new Animated.Value(50),
fadeAnim2: new Animated.Value(50),
}
componentDidMount() {
}
animatebutton() {
Animated.timing( // Animate over time
this.state.fadeAnim, // The animated value to drive
{
toValue: screenheight,
duration: 10000, // Make it take a while
}
).start();
Animated.timing( // Animate over time
this.state.fadeAnim2, // The animated value to drive
{
toValue: screenwidth,
duration: 10000, // Make it take a while
}
).start(); // Starts the animation
}
render() {
let { fadeAnim,fadeAnim2 } = this.state;
return (
<Animated.View // Special animatable View
style={{
...this.props.style,
height: fadeAnim,
width : fadeAnim2
}}
>
{this.props.children}
</Animated.View>
);
}
}
// You can then use your `FadeInView` in place of a `View` in your components:
export default class App extends React.Component {
constructor(props){
super(props);
this.state={
}
}
animatebutton(){
this.fade.animatebutton();
}
render() {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}} >
<FadeInView style={{backgroundColor: 'powderblue'}} ref={ani => this.fade = ani}>
<Text style={{fontSize: 28, textAlign: 'center', margin: 10}}>Fading in</Text>
</FadeInView>
<Button title="go animate" onPress={() => this.animatebutton()}/>
</View>
)
}
}
OR
You can use LayoutAnimation that you want to use. Look at my example.
import React, {Component} from "react";
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
LayoutAnimation,
} from 'react-native';
class App extends Component {
constructor() {
super();
this.state = {
check: false,
}
}
onPresscheck() {
// Uncomment to animate the next state change.
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
// Or use a Custom Layout Animation
// LayoutAnimation.configureNext(CustomLayoutAnimation);
this.setState({ check : !this.state.check});
}
render() {
var middleStyle = this.state.check === false ? {width: 20,height:20} : {width: "100%",height:"100%"};
return (
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={() => this.onPresscheck()}>
<Text>pressbutton</Text>
</TouchableOpacity>
<View style={[middleStyle, {backgroundColor: 'seagreen'}]}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
button: {
width:"100%",
height: 60,
backgroundColor: 'blue',
alignItems: 'center',
justifyContent: 'center',
margin: 8,
},
});
export default App;
Please refer to this blog :
https://dev-yakuza.github.io/en/react-native/react-native-animatable/
Also, try using this library. Use any animation type you want and render them.
Happy coding :)

style activityIndicator in react-native

I am trying to set the color of my ActivityIndicator:
<View style={[{height: this.props.calendarHeight}, this.style.placeholder]}>
<ActivityIndicator size="large" color={this.style.loadingSpinner.color} />
</View>
I am setting my style here:
import React, {Component} from 'react';
import {Text, View, ActivityIndicator} from 'react-native';
import Calendar from '../calendar';
import styleConstructor from './style';
class CalendarListItem extends Component {
constructor(props) {
super(props);
this.style = styleConstructor(props.theme);
}
shouldComponentUpdate(nextProps) {
const r1 = this.props.item;
const r2 = nextProps.item;
return r1.toString('yyyy MM') !== r2.toString('yyyy MM') || !!(r2.propbump && r2.propbump !== r1.propbump);
}
render() {
const row = this.props.item;
if (row.getTime) {
return (
<Calendar
theme={this.props.theme}
style={[{height: this.props.calendarHeight}, this.style.calendar]}
current={row}
hideArrows
hideExtraDays={this.props.hideExtraDays === undefined ? true : this.props.hideExtraDays}
disableMonthChange
markedDates={this.props.markedDates}
markingType={this.props.markingType}
hideDayNames={this.props.hideDayNames}
onDayPress={this.props.onDayPress}
minDate={this.props.minDate}
maxDate={this.props.maxDate}
firstDay={this.props.firstDay}
monthFormat={this.props.monthFormat}
dayComponent={this.props.dayComponent}
disabledByDefault={this.props.disabledByDefault}
showWeekNumbers={this.props.showWeekNumbers}
/>);
} else {
const text = row.toString();
return (
<View style={[{height: this.props.calendarHeight}, this.style.placeholder]}>
<ActivityIndicator size="large" color={this.style.loadingSpinner} />
</View>
);
}
}
}
export default CalendarListItem;
My style.js is:
import {StyleSheet} from 'react-native';
import * as defaultStyle from '../style';
const STYLESHEET_ID = 'stylesheet.calendar-list.main';
export default function getStyle(theme={}) {
const appStyle = {...defaultStyle, ...theme};
return StyleSheet.create({
container: {
backgroundColor: appStyle.calendarBackground
},
placeholder: {
backgroundColor: appStyle.calendarBackground,
alignItems: 'center',
justifyContent: 'center'
},
placeholderText: {
fontSize: 30,
fontWeight: '200',
color: appStyle.dayTextColor
},
loadingSpinner: {
color: '#fff'
},
calendar: {
paddingLeft: 15,
paddingRight: 15
},
...(theme[STYLESHEET_ID] || {})
});
}
However, this.style.loadingSpinner.color is undefined.
How can set the color?
use the CSS transform will make the icon bigger
<ActivityIndicator size="large" style={{ transform: [{ scaleX: 2 }, { scaleY: 2 }] }} color="#E85F5C" />
To set the color of ActivityIndicator component, just set the prop color to what you want, like this
<ActivityIndicator color={colors.yourColor} /> // if you have an object with your colors
or
<ActivityIndicator color='#000' />
You can also change the size of this component with the prop size
<ActivityIndicator size='small' /> // you can set 'small' or 'large'
remember to import ActivityIndicator from 'react-native'
You can give the custom styling doing something like -
<ActivityIndicator
animating = {animating}
color = '#bc2b78' // color of your choice
size = "large"
style = {styles.activityIndicator}/> //add extra styling
// add style something like this -
activityIndicator: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
height: 80
}