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

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 :)

Related

How to show loading progress or spinner in the middle of the screen with React Native?

I am developing React Native app.
I was able to solve all problems by myself but this is exception.
I am going to load another screen with bottom tab navigator.
For example, after user login to the app, it should show main home screen which has many pictures and many style sheet effects, icons. Because of that, after login confirm ( I mean after alert of the login confirm), the main home screen appears after a few seconds.
So I want to show some spinner in the login screen while loading main home screen in the background and when it is ready to show, erase spinner and show main home screen.
How can I do this?
My bottom tab navigator was simply created with createBottomTabNavigator() method.
So in your case you can do several things
You can use React Native Activity Indicator -> View
You can use Overlay Library -> react-native-loading-spinner-overlay -> View GitHub
If you like to make loading like facebook / instagram -> then use react-native-easy-content-loader -> View GitHub
Assume that you are using React Native Activity Indicator :
import { ActivityIndicator } from "react-native";
export default class HomeScreen extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true
};
}
//Get Home Screen Data API Action
componentDidMount() {
this.loadAPI(); // Call home screen get data API function
}
//Login API Function
loadAPI = () => {
this.setState({ isLoading: true }); // Once You Call the API Action loading will be true
fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(responseText => {
// You can do anything accroding to your API response
this.setState({ isLoading: false }); // After getting response make loading to false
})
.catch(error => {});
};
render() {
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
{this.state.isLoading && <ActivityIndicator color={"#fff"} />}
</View>
);
}
}
If you want to hide all the view until loading finish like images, so you can use custom library instead of Activity Indicator.
I have created my custom Loader component. Using this you can display built in ActivityIndicator or your custom gif loader image with overlay.
Loader.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
Modal,
Image,
ActivityIndicator
} from 'react-native';
class Loader extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: this.props.isLoading
}
}
static getDerivedStateFromProps(nextProps) {
return {
isLoading: nextProps.isLoading
};
}
render() {
return (
<Modal
transparent={true}
animationType={'none'}
visible={this.state.isLoading}
style={{ zIndex: 1100 }}
onRequestClose={() => { }}>
<View style={styles.modalBackground}>
<View style={styles.activityIndicatorWrapper}>
<ActivityIndicator animating={this.state.isLoading} color="black" />
{/* If you want to image set source here */}
{/* <Image
source={require('../assets/images/loader.gif')}
style={{ height: 80, width: 80 }}
resizeMode="contain"
resizeMethod="resize"
/> */}
</View>
</View>
</Modal>
)
}
}
const styles = StyleSheet.create({
modalBackground: {
flex: 1,
alignItems: 'center',
flexDirection: 'column',
justifyContent: 'space-around',
backgroundColor: '#rgba(0, 0, 0, 0.5)',
zIndex: 1000
},
activityIndicatorWrapper: {
backgroundColor: '#FFFFFF',
height: 100,
width: 100,
borderRadius: 10,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-around'
}
});
export default Loader
Now you can use it when you have to display loading indicator as below :
<Loader isLoading={this.state.isLoading} />
import { ActivityIndicator } from 'react-native';
export default class LoginScreen extends Component {
constructor(props) {
super(props);
this.state = {
spinner : true
}
}
render() {
return (
<View style={{flex : 1, justifyContent: 'center', alignItems: 'center',}}>
{
this.state.spinner &&
<ActivityIndicator color={'#fff'} />
}
</View>
)
}
}
So you can show the SPinner for suppose when you have to load an API or something and when you get the response of api, you can set spinner loading value to false.
For eg :
import {View, ActivityIndicator } from 'react-native';
export default class MainScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
spinner : true
}
}
componentDidMount(){
this.loadApi();
}
loadApi = async() => {
let result = axios.get('url').then((data) =>{
this.setState({spinner:false});
}
).catch((err) => this.setState({spinner:false})
}
render() {
return (
<View style={{flex : 1, justifyContent: 'center', alignItems: 'center',}}>
{
this.state.spinner? <ActivityIndicator color={'#fff'} />:<View><Text>Data loaded</Text></View>
}
</View>
)
}
}
you have to use ActivityIndicator you can have to load this activityindicator before getting data from the server , you have to check below code hope you will understand
import React, {useEffect, useState} from 'react';
import {ActivityIndicator, View, Dimensions} from 'react-native';
import HomeScreen from './Home';
const DataViewer = () => {
const [data, setData] = useState([]);
const {height, width} = Dimensions.get('window');
useEffect(() => {
fetch('http://example.com/movies.json')
.then(response => {
return response.json();
})
.then(myJson => {
setData(myJson);
});
});
return data.length > 0 ? (
<HomeScreen data={data} />
) : (
<View
style={{justifyContent: 'center', alignItems: 'center', height, width}}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
);
};
export default DataViewer;
You can use the Activity indicator as the default loading animation. But you can also use Lottie files to implement custom loading screen animation on your project by installing npm i lottie-react-native or yarn add lottie-react-native

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

Implementing multiple Progress.bar in react-native

I want to achieve the WhatsApp stories like effect, where the number of progress bars on top are equal to the number of stories.
I'm using react-native-progress/bar library to achieve this effect, but I'm finding a way that how can I run second progress bar when first ends.
Actually progress of Progress.bar changes with the change of state.
What is an efficient way to do this by using a single state?
Here is code:
import React, { Component } from 'react';
import { StyleSheet, TouchableOpacity, View } from 'react-native';
import * as Progress from 'react-native-progress';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
image: {
width: 300,
height: 200,
},
});
export default class Example extends Component {
componentDidMount() {
this.animate();
}
constructor(props) {
super(props);
this.state = {
progress: 0
};
}
animate() {
let progress = 0;
this.setState({ progress });
let myInterval = setInterval(() => {
if (progress > 1) {
progress = 1;
clearInterval(myInterval);
} else {
progress += 0.01;
}
this.setState({ progress });
}, 20)
}
render() {
return (
<View style={styles.container}>
<View style={{flexDirection:'row'}} >
<Progress.Bar
key={'0'}
style={styles.progress}
progress={this.state.progress}
indeterminate={false}
/>
<Progress.Bar
key={'1'}
style={styles.progress}
progress={this.state.progress}
indeterminate={false}
/>
</View>
</View>
);
}
}

Callback after the end of animation in react-navigation

Using react-navigation with react-native.
How can jeg run a function at the end of animation?
So I want callback like
navigate('RoadObject', () => { at the end of animationto do something... });
My tab navigator:
const MainNavigator = TabNavigator({
Map: {
screen: MapScreen
},
RoadObject: {
screen: RoadObjectScreen
}
},
{
animationEnabled: true
});
Have you tried Transitioner | React Navigation?
Seems like this might be relevant for your case...
Transitioner is a React component that helps manage transitions for complex animated components. It manages the timing of animations and keeps track of various screens as they enter and leave, but it doesn't know what anything looks like, because rendering is entirely deferred to the developer.
Under the covers, Transitioner is used to implement CardStack, and hence the StackNavigator.
The most useful thing Transitioner does is to take in a prop of the current navigation state. When routes are removed from that navigation state, Transitioner will coordinate the transition away from those routes, keeping them on screen even though they are gone from the navigation state.
Example
class MyNavView extends Component {
...
render() {
return (
<Transitioner
configureTransition={this._configureTransition}
navigation={this.props.navigation}
render={this._render}
onTransitionStart={this.onTransitionStart}
onTransitionEnd={this.onTransitionEnd}
/>
);
}
I had some problem with transictions too. I was entering on a Screen with Camera and it got too slow. So I decided to keep the Camera off before finishing the transition animation and after that I turned it on.
Example:
import React, {Component, createRef, RefObject} from 'react';
import {SafeAreaView, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {Camera} from 'expo-camera';
import {CameraType} from 'expo-camera/build/Camera.types';
import {FontAwesome} from '#expo/vector-icons';
import {StackNavigationProp} from "#react-navigation/stack/lib/typescript/src/types";
export interface State {
type: CameraType,
hasPermission: boolean | null,
takenPictures: Array<string>,
isNavigating: boolean,
}
export interface Props {
navigation: StackNavigationProp<any>,
}
export class CameraMan extends Component<Props, State> {
private readonly camera: RefObject<Camera>;
constructor(props: Props) {
super(props);
this.camera = createRef();
this.state = {
type: Camera.Constants.Type.back,
hasPermission: null,
takenPictures: [],
isNavigating: true
}
}
async componentDidMount() {
this.props.navigation.addListener('transitionEnd', e => {
this.setState({
isNavigating: false
});
});
let permissionResponse = await Camera.requestPermissionsAsync();
this.setState({
hasPermission: permissionResponse.granted
});
}
render() {
if (this.state.hasPermission == null) {
return <SafeAreaView style={styles.container}>
</SafeAreaView>;
}
if (!this.state.hasPermission) {
return <SafeAreaView style={styles.container}>
<Text>Acesso negado!</Text>
</SafeAreaView>;
}
return (
<SafeAreaView style={styles.container}>
{
(this.state.isNavigating) ?
<View style={{flex: 1, backgroundColor: '#000'}} />
:
<Camera style={{flex: 1}}
type={this.state.type}
ref={this.camera}>
<View style={{flex: 1, backgroundColor: 'transparent', flexDirection: 'row'}}>
<TouchableOpacity style={{
position: 'absolute',
bottom: 20,
left: 20,
}}
onPress={() => this.switchCameraType()}>
<Text style={{fontSize: 20, marginBottom: 13, color: '#FFF'}}>Trocar</Text>
</TouchableOpacity>
</View>
</Camera>
}
<TouchableOpacity style={{
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#121212',
margin: 20,
borderRadius: 10,
height: 50,
}} onPress={() => this.takePicture()}>
<FontAwesome name="camera" size={23} color="#FFF" />
</TouchableOpacity>
</SafeAreaView>
);
}
private async takePicture() {
const capturedPicture = await this.camera.current?.takePictureAsync();
console.log(capturedPicture?.uri);
}
private switchCameraType() {
const selectedCameraType = this.state.type == Camera.Constants.Type.back ? Camera.Constants.Type.front : Camera.Constants.Type.back;
this.setState({type: selectedCameraType});
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
}
});
Based on this: https://reactnavigation.org/docs/navigation-events/

How can I change the text in TabBarIOS in React Native?

In the react native documentation I cannot find a way to change the bottom words?
<TabBarItemIOS
name="greenTab"
icon={_ix_DEPRECATED('more')}
accessibilityLabel="Green Tab"
selected={this.state.selectedTab === 'greenTab'}
onPress={() => {
this.setState({
selectedTab: 'greenTab',
presses: this.state.presses + 1
});
}}>
{this._renderContent('#21551C', 'Green Tab')}
</TabBarItemIOS>
What is the accessibilityLabel ?
The TabBarItem allows you to use one of the iOS preset icons from UITabBarSystemItem, and in your sample code it's using the "More" icon. Crucially though, the documentation for UITabBarSystemItem states:
The title and image of system tab bar items cannot be changed.
If you set the icon to either a data-uri or a local image, rather than an icon from UITabBarSystemItem, you'll be able to override the text on the item to whatever you want using the title prop.
You can try something like that for your TabBarIOS.Item with a custom icon
import React, { Component } from 'react'
import { AppRegistry, StyleSheet, Text, View, TouchableOpacity, TabBarIOS } from 'react-native'
const base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg=='
class ReactNativePlayground extends Component {
constructor(props) {
super(props)
this.state = {
selectedTab: "more",
tabBarItemTitle: "More"
}
}
render() {
return (
<TabBarIOS>
<TabBarIOS.Item selected={this.state.selectedTab === "more"}
title={this.state.tabBarItemTitle}
icon={{uri: base64Icon, scale: 3}}>
<View style={styles.container}>
<TouchableOpacity onPress={ (event) => { this._changeTabItemTitle() } }>
<Text style={styles.button}>Tap to Change Item Title</Text>
</TouchableOpacity>
</View>
</TabBarIOS.Item>
</TabBarIOS>
);
}
_changeTabItemTitle() {
this.setState({ tabBarItemTitle: "New More" })
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
button: {
fontSize: 20,
color: "white",
textAlign: 'center',
backgroundColor: "#1155DD",
borderRadius: 5,
height: 30,
margin: 30,
},
});
AppRegistry.registerComponent('ReactNativePlayground', () => ReactNativePlayground);