How to highlight a single button in react native? - javascript

How can I highlight a single button surrounded by multiple buttons?
Here is my component that renders the button. Also, I imported a CustomButton that I created a while ago.
const button = [
{
title: '#Food',
selected: false,
id: 1
},
{
title: '#Fashion',
selected: false,
id: 2
},
{
title: '#Art',
selected: false,
id: 3
}]
{button.map(({ title, id, selected }) => {
return (
<View style={{ width: '25%', padding: 5, }}>
<CustomButton
bgColor={active ? 'red' : 'blue'}
title={title}
key={id}
onPress={() => chosenButton(selected, id)}
textColor={Colors.PRIMARY_COLOR} />
</View>
)
})}
Here is my CustomButton
const CustomButton = ({ title, containerStyle, textStyle, bgColor, textColor, onPress }) => {
return (
<Button onPress={onPress} block rounded style={[styles.btnStyle, containerStyle, { backgroundColor: bgColor, }]}>
<Text style={[styles.text, textStyle, { color: textColor }]}>{title}</Text>
</Button>
);
};
As of now, here is my buttons
But I want to highlight a single button and change the background color of it if clicked. How can I do that?

You could do useState in child component and change the colour on click
const CustomButton = ({ title, containerStyle, textStyle, bgColor, textColor, onPress }) => {
const [bgCol,setBgCol] = useState(bgColor);
const changeBg = () => setBgCol('yellow');
return (
<Button onPress={()=>{changeBg();onPress()}} block rounded style={[styles.btnStyle, containerStyle, { backgroundColor: bgCol, }]}>
<Text style={[styles.text, textStyle, { color: textColor }]}>{title}</Text>
</Button>
);
};

In order to persist the selected value in the buttons array, you can do like
const [button, setButton] = useState([
{
title: '#Food',
selected: false,
id: 1
},
{
title: '#Fashion',
selected: false,
id: 2
},
{
title: '#Art',
selected: false,
id: 3
}]);
const handleButtonClick = (index) => {
const newData = [...button];
newData[index].selected = !newData[index].selected;
setButton(newData);
}
{button.map(({ title, id, selected }, index) => {
return (
<View style={{ width: '25%', padding: 5, }}>
<CustomButton
bgColor={selected ? 'red' : 'blue'}
....
onPress={() => handleButtonClick(index)}
/>
</View>
)
})}

Related

React Native : change View color when TouchableOpacity is pressed

I have 2 TouchableOpacity each having a View inside it.
I need to change View's backgroundColor to blue when its TouchableOpacity is pressed and to return to the initial backgroundColor when its TouchableOpacity is pressed a second time.
Here I don't want to use state because I have 2 or more TouchableOpacity so I need to have a state for every component.
Here is my code:
<TouchableOpacity>
<View style={{backgroundColor:'green'}}>
</View>
</TouchableOpacity>
<TouchableOpacity>
<View style={{backgroundColor:'yellow'}}>
</View>
</TouchableOpacity>
You can do this by using a single state and change backgroundColor by checking its value for ex:
Initial a data it contain id and initial color:
const DATA = [
{
id: 1,
isSelected: false,
initialBg: 'green',
},
{
id: 2,
isSelected: false,
initialBg: 'red',
},
{
id: 3,
isSelected: false,
initialBg: 'yellow',
},
{
id: 4,
isSelected: false,
initialBg: 'black',
},
];
Here I initialise the isSelected to false and initial color to a id, Now we need to change isSelected to true and change its color to blue when user taps on that button.
const [isSelected, setIsSelected] = useState(DATA);
const onItemSelect = (item) => {
let newState;
if (item.isSelected) {
newState = isSelected.map((isSelectedItem) =>
isSelectedItem.id === item.id
? {...isSelectedItem, isSelected: false}
: {...isSelectedItem},
);
} else {
newState = isSelected.map((isSelectedItem) =>
isSelectedItem.id === item.id
? {...isSelectedItem, isSelected: true}
: {...isSelectedItem},
);
}
setIsSelected(newState);
};
return(
<View>
{isSelected.map((item) => (
<TouchableOpacity onPress={() => onItemSelect(item)} key={item.id}>
<View
style={{
backgroundColor: item.isSelected ? 'blue' : item.initialBg,
width: 50,
height: 50,
}}></View>
</TouchableOpacity>
))}
</View>
)

React Native - Changing the indicator width according to tab bar text width (react-native-tab-view)

I am using react-native-tab-view, and trying to change the indicator width. I would like indicator width to be the same with the tab text. But What I did is just the default. I have tried in many ways, but always it gave me the wrong result. The tab bar should be scrollable horizontally as well. Could you check which part I should change?
This is the expected result :
ShowAllIndex Code :
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.dark,
},
});
const ShowAllIndex = () => {
const { seller } = useSelector((s) => s.auth, shallowEqual);
const [routes] = useState([
{ key: 'best', title: 'BEST' },
{ key: 'jacket', title: '아우터' },
{ key: 'pants', title: '바지' },
{ key: 'skirts', title: '스커트' },
{ key: 'topClothe', title: '원피스' },
{ key: 'one', title: '바지' },
{ key: 'two', title: '스커트' },
{ key: 'three', title: '상의' },
]);
const renderScene = SceneMap({
best: ShowAllMainRoutes,
jacket: JacketRoutes,
pants: PantsRoutes,
skirts: SkirtsRoutes,
topClothe: TopClotheRoutes,
one: ShowAllMainRoutes,
two: JacketRoutes,
three: PantsRoutes,
});
return (
<ScrollView style={[styles.container, { marginTop: Global() }]}>
<CustomTabView
routes={routes}
renderScene={renderScene}
scrollEnabled={true}
tabStyle={{ width: 'auto' }}
showAll={true}
/>
</ScrollView>
);
};
export default ShowAllIndex;
CustomTabView code :
const initialLayout = { width: Dimensions.get('window').width };
const CustomTabView = ({
routes,
renderScene,
numberOfTabs,
indicatorWidth,
scrollEnabled = false,
tabStyle,
showAll,
indicatorStyle,
}) => {
const [index, setIndex] = useState(0);
const renderTabBar = (props) => (
<TabBar
{...props}
scrollEnabled={scrollEnabled}
indicatorStyle={[
indicatorStyle,
{
backgroundColor: colors.barbie_pink,
height: 2.5,
bottom: -1,
},
]}
style={[styles.tabBar]}
renderLabel={({ route, focused }) => {
return (
<Text
style={[styles.label, focused ? styles.activeLabel : styles.label]}
>
{route.title}
</Text>
);
}}
tabStyle={tabStyle}
/>
);
return (
<TabView
navigationState={{ index, routes }}
renderScene={renderScene}
renderTabBar={renderTabBar}
onIndexChange={setIndex}
initialLayout={initialLayout}
style={[styles.container]}
/>
);
};
const styles = StyleSheet.create({
container: {
backgroundColor: colors.dark,
},
scene: {
flex: 1,
marginTop: 5,
},
tabBar: {
backgroundColor: 'transparent',
shadowOpacity: 0,
elevation: 0,
borderBottomWidth: 0.5,
borderColor: colors.very_light_pink_two,
marginBottom: 5,
},
label: {
color: colors.very_light_pink_four,
fontSize: 14,
lineHeight: 20.8,
fontFamily: 'NotoSansCJKkr-Regular',
letterSpacing: -0.35,
},
activeLabel: {
color: colors.barbie_pink,
},
});
Thank you for answers!
Check this solution:
const TAB_MARGIN = 24;
<TabBar
...
scrollEnabled
renderIndicator={indicatorProps => {
const width = indicatorProps.getTabWidth(this.state.index) - TAB_MARGIN
return <TabBarIndicator {...indicatorProps} width={width} />
}}
indicatorStyle={{
backgroundColor: '#333',
height: 4,
left: TAB_MARGIN / 2,
}}
...
/>
I think the prop indicatorStyle in TabBar that can resolves you problem.
You can do the following:
<TabBar
scrollEnabled //add this line to make it scrollable
tabStyle={{width: 100}} //and this one to change the tab width
/>

react-native , customer flatlist picker, returning previous values on selection

Below is the code component for the customer picker
import React, { useEffect, useState } from "react";
import { connect } from 'react-redux';
import {
TouchableOpacity,
FlatList,
SafeAreaView,
StatusBar,
StyleSheet,
Text,
View,
Button,
Alert,
} from "react-native";
import { screenHeight, screenWidth } from "../constants";
const DATA = [
{
id: "bd7acbea-c1b1-46c2-aed5-3ad53abb28ba",
title: "Client Not Found"
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d72",
title: "Client refused"
},
];
const Item = ({ item, onPress, style }) => (
<TouchableOpacity onPress={onPress} style={[styles.item, style]}>
<Text style={styles.title}>{item.title}</Text>
</TouchableOpacity>
);
const StatusOptions = (props) => {
const [selectedId, setSelectedId] = useState(null);
const renderSeparator = () => (
<View
style={{
backgroundColor: "grey",
height: 0.8
}}
/>
);
const ListHeader = () => {
//View to set in Header
return (
<View style={{ height: 20 }}></View>
);
};
const renderItem = ({ item }) => {
const backgroundColor = item.id === selectedId ? "#6cd9ff" : "white";
return (
<Item
item={item}
onPress={() => {
setSelectedId(item.id);
console.log("SELECTED ID _ STATUSOPTIONS component : ", selectedId);
const val = DATA.filter(status => status.id == selectedId).map(filteredStatus => filteredStatus.title);
console.log("VALLLLLLLLLLLLLLLLLLLLLLLUUUUUUEEEEEEEEEEEEEEEEEEEE:::: ", val);
props.navigation.navigate('AnotherScreen');
}}
style={{ backgroundColor }}
/>
);
};
return (
<View style={{ bottom: 0, flex: 1, position: 'absolute', width: screenWidth, }}>
<View style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={(item) => item.id}
extraData={selectedId}
ItemSeparatorComponent={renderSeparator}
ListHeaderComponent={ListHeader}
style={{
backgroundColor: "white",
width: "100%",
borderTopRightRadius: 20,
borderTopLeftRadius: 20,
zIndex: 1,
}}
/>
</View>
<View style={{ backgroundColor: "grey", height: 0.4 }} />
<View style={styles.closeButtonContainer}>
<TouchableOpacity style={styles.closeButton}
onPress={() => {
props.setStatusOptionsVisible(false)
}}>
<Text style={styles.title}>Close</Text>
</TouchableOpacity>
</View>
</View>
);
};
function mapStateToProps(state) {
return {
StatusOptionsVisible: state.volunteerItems.statusOptionsVisible,
currentTaskItemId: state.taskItems.taskItemId,
};
}
function mapDispatchToProps(dispatch) {
return {
setStatusOptionsVisible: (visible) => dispatch({ type: 'SET_STATUS_VISIBLE', statusVisibility: visible }),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(StatusOptions);
const styles = StyleSheet.create({
closeButton: {
backgroundColor: 'lightgrey',
borderRadius: 10,
height: 50,
justifyContent: 'center',
width: '90%',
},
closeButtonContainer: {
alignItems: 'center',
height: 90,
justifyContent: 'center',
backgroundColor: 'white',
},
textStyle: {
textAlign: "center",
},
container: {
borderRadius: 30,
flex: 4,
width: screenWidth,
},
item: {
padding: 20
},
title: {
fontSize: 20,
fontWeight: 'bold',
color: "black",
textAlign: "center"
}
});
the console Log : ("SELECTED ID _ STATUSOPTIONS component : ", selectedId)
in render Item function returns null for first picker item selection and the returns the previous value for the next picker item selection , can anyone please help with fixing it ?
Try to use this
useEffect(() => {
console.log("SELECTED ID _ STATUSOPTIONS component : ", selectedId);
if(selectedId != null) {
const val = DATA.filter(status => status.id == selectedId).map(filteredStatus => filteredStatus.title);
console.log("VALLUUEEEEEEEEEEEEEEEEEEEE:::: ", val);
}
}, [selectedId])

React native flatlist multiple selection is not updating

I am using a flatlist to expose all the list of ingredients I have saved on my database, but once I update the state, it is not reflecting on the flatlist component.
The flatlist component
<FlatList
horizontal
bounces={false}
key={ingredientList.id}
data={ingredientList}
renderItem={({ item }) => (
<TouchableOpacity onPress={() => selectedIngredient(item)}>
<Card key={item.id}>
<Text key={item.title} style={styles.titleText}>{item.name}</Text>
<Text key={item.title} style={styles.titleText}>{item.isSelected?'selected':'not selected'}
</Text>
<ImageBackground key={item.illustration} source={item.illustration} style={styles.cardImage}>
</ImageBackground>
</Card>
</TouchableOpacity>
)}
keyExtractor={(item) => item.index}
/>
This is the function that find the selected item "selectedIngredient"
function selectedIngredient(item) {
console.log('received: ', item.name)
item.isSelected = !item.isSelected;
return { ...item.isSelected }
}
That component call is working when I try debbug with console.log after the "item.isSelected = !item.isSelected", but the IU is not updated. Can someone help me to understand how to fix it?
You need to set state by using either setState in a class-based component or either using useState hook in the functional component.
function selectedIngredient(item) {
console.log('received: ', item.name)
item.isSelected = !item.isSelected; //this is not how you set state
return { ...item.isSelected }
}
Screenshot:
here is our old example which I modified for your current scenario:
import React, { useState } from 'react';
import {
Text,
View,
StyleSheet,
FlatList,
TouchableOpacity,
} from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
// or any pure javascript modules available in npm
const ingredientList = [
{
id: 1,
name: 'item1',
selected: false,
},
{
id: 2,
name: 'item 2',
selected: false,
},
{
id: 3,
name: 'item 3',
selected: false,
},
{
id: 8,
name: 'item 4',
selected: false,
},
{
id: 4,
name: 'item 5',
selected: false,
},
{
id: 5,
name: 'item 6',
selected: false,
},
];
export default function App() {
const [selectedItem, setSelectedItem] = useState(null);
const [allItems, setAllItems] = useState(ingredientList);
const selectedIngredient = (item) => {
console.log('selecionado: ' + item.name);
setSelectedItem(item);
/* Below operation can be improved by passing index to the function itself.
so filtering would not be required
*/
let temp = allItems.filter((parentItem) => parentItem.id !== item.id);
item.selected = !item.selected;
temp = temp.concat(item);
temp.sort((a, b) => parseInt(a.id) - parseInt(b.id));
setAllItems(temp);
console.log(allItems);
};
return (
<View style={styles.container}>
<FlatList
style={styles.flatlist}
horizontal
bounces={false}
data={allItems}
renderItem={({ item }) => (
<TouchableOpacity
style={styles.flatListItem}
key={item.id}
onPress={() => selectedIngredient(item)}>
<Text>{item.name}</Text>
{!item.selected ? (
<Text style={{ color: 'red' }}>{'Not Selected'}</Text>
) : (
<Text style={{ color: 'green' }}>{'Selected'}</Text>
)}
</TouchableOpacity>
)}
keyExtractor={(item) => item.index}
/>
{selectedItem ? (
<View style={styles.selectedTextView}>
<Text style={styles.selectedText}>{`${selectedItem.name} ${
selectedItem.selected ? 'selected' : 'not selected'
}`}</Text>
</View>
) : (
<View style={styles.selectedTextView}>
<Text style={styles.selectedText}>{`Nothing selected`}</Text>
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
flatListItem: {
width: 100,
height: 100,
backgroundColor: 'white',
margin: 5,
borderRadius: 10,
justifyContent: 'center',
alignItems: 'center',
},
selectedTextView: {
flex: 8,
backgroundColor: 'white',
margin: 5,
borderRadius: 10,
justifyContent: 'center',
alignItems: 'center',
fontSize: 20,
},
selectedText: {
fontSize: 30,
},
});
Live Demo

React Native Props

I am new to React Native. I am making a music app and I'm using the react-native-track-player module which works. But now, I'm trying to pass songlist as props from my Flatlist to the player component.
So first, I am able to show the moods. Then when I pass props/move to Songlist screen I am be able to show the songlist and it will display the title and artist in a Flatlist. So when I click on one of them, It will go to the Play screen. I want to be able to pass the props and play the song. But the song will not be played and crash. I am not sure whether I am passing the props properly. I will really appreciate if anyone can help me with this issue.
This is my Cluster1 screen (first screen)
export default class Cluster1 extends Component{
render(){
return(
<View style={styles.container}>
<SectionList
renderItem={({item,index})=>{
return(
<SectionListItem item={item} index={index}> </SectionListItem>);}}
renderSectionHeader={({ section }) => {
return (<SectionHeader section={section} />);}}
sections={ClusterData}
keyExtractor={(item, index) => item.name}>
</SectionList>
</View>
);
}}
class SectionHeader extends Component {
render() {
return (
<View style={styles.header}>
<Text style={styles.headertext}>
{this.props.section.title}
</Text>
<TouchableOpacity onPress={ () => Actions.SongList({ section: this.props.section}) }>
<Text style ={styles.Play}> Play
</Text>
</TouchableOpacity>
</View>
);
}}
class SectionListItem extends Component{
render(){
return(
<View>
<Text style={styles.moodname}>{this.props.item.name}</Text>
</View>
);
}
}
This is my SongList screen (second screen)
export default class App extends Component {
render() {
return (
<View>
<FlatList
data={this.props.section.songlist}
renderItem={({item,index,rowId})=>{
return(
<FlatListItem item={item} index={index}>
</FlatListItem>);}}>
</FlatList>
</View>
);}}
class FlatListItem extends Component{
render(){
return(
<View>
<TouchableOpacity onPress={ () => Actions.Play({songIndex: 0, songlist: this.props.item.songlist, item: this.props.item}) }>
<Text style={styles.itemTitle}>{this.props.item.songtitle}</Text>
<Text style={styles.itemArtist}>{this.props.item.artist}</Text>
</TouchableOpacity>
</View>
);}}
So when I click on the songtitle/artist, the app will stop. I think the error could be await TrackPlayer.add(this.props.item.songlist); but I am not sure.
This is my Play screen
import TrackPlayer from 'react-native-track-player';
export default class Play extends Component{
componentDidMount()
{
TrackPlayer.setupPlayer().then(async () => {
// Adds a track to the queue
await TrackPlayer.add(this.props.item.songlist);
// Starts playing it
TrackPlayer.play();
});
}
onPressPlay = () => {
TrackPlayer.play();
};
onPressPause = () => {
TrackPlayer.pause();
};
render() {
return (
<View style={styles.container}>
<View style= {{flexDirection :'column'}}>
<TouchableOpacity style= {styles.play} onPress = {this.onPressPlay}>
<Text style = {{fontWeight:'bold',textAlign:'center',color:'white'}}>Play</Text>
</TouchableOpacity>
<TouchableOpacity style= {styles.pause} onPress = {this.onPressPause}>
<Text style = {{fontWeight:'bold',textAlign:'center',color:'white'}}>Pause</Text>
</TouchableOpacity>
</View>
</View>
);}}
This is my where I get my data in another file
const ClusterData = [
{ title: 'Cluster1',
data:
[
{name: 'passionate'},
{name: 'rousing'},
{name: 'confident'},
{name: 'boisterous'},
{name: 'rowdy'}
],
songlist:
[
{
id: '2222',
url: 'http://tegos.kz/new/mp3_full/Post_Malone_-_Better_Now.mp3',
title: 'Better Now',
artist: 'Post Malone',
},
{
id: '2',
url: 'http://tegos.kz/new/mp3_full/5_Seconds_Of_Summer_-_Youngblood.mp3',
title: 'YoungBlood',
artist: '5SOS',
},
]
},
{ title: 'Cluster2',
data:
[
{name: 'rollicking'},
{name: 'cheerful'},
{name: 'fun'},
{name: 'sweet'},
{name: 'amiable'},
{name: 'natured'}
],
songlist:
[
{
id: '1111',
url: 'http://tegos.kz/new/mp3_full/Yellow_Claw_and_San_Holo_-_Summertime.mp3',
title: 'Summertime',
artist: 'Yellow Claw',
},
{
id: '1',
url: 'http://tegos.kz/new/mp3_full/Luis_Fonsi_feat._Daddy_Yankee_-_Despacito.mp3',
title: 'Despacito',
artist: 'Luis Fonsi',
},
]
},
You are passing wrong props in FlatListItem, now there is no songlist object beacause item itself is a songlist item,
So just pass it like this Actions.Play({songIndex: 0, item: this.props.item}) }> and Update inside Play class by replacing this.props.item.songlist to this.props.item
Below is the complete working example
import React, { Component } from 'react';
import {
View,
Text,
FlatList,
TouchableOpacity,
SectionList,
} from 'react-native';
import TrackPlayer from 'react-native-track-player';
const ClusterData = [
{
title: 'Cluster1',
data: [
{ name: 'passionate' },
{ name: 'rousing' },
{ name: 'confident' },
{ name: 'boisterous' },
{ name: 'rowdy' },
],
songlist: [
{
id: '2222',
url: 'http://tegos.kz/new/mp3_full/Post_Malone_-_Better_Now.mp3',
title: 'Better Now',
artist: 'Post Malone',
},
{
id: '2',
url:
'http://tegos.kz/new/mp3_full/5_Seconds_Of_Summer_-_Youngblood.mp3',
title: 'YoungBlood',
artist: '5SOS',
},
],
},
{
title: 'Cluster2',
data: [
{ name: 'rollicking' },
{ name: 'cheerful' },
{ name: 'fun' },
{ name: 'sweet' },
{ name: 'amiable' },
{ name: 'natured' },
],
songlist: [
{
id: '1111',
url:
'http://tegos.kz/new/mp3_full/Yellow_Claw_and_San_Holo_-_Summertime.mp3',
title: 'Summertime',
artist: 'Yellow Claw',
},
{
id: '1',
url:
'http://tegos.kz/new/mp3_full/Luis_Fonsi_feat._Daddy_Yankee_-_Despacito.mp3',
title: 'Despacito',
artist: 'Luis Fonsi',
},
],
},
];
export class MusicPlayer extends Component {
state = {
showSongList: false,
activeSection: null,
};
updateState = item => {
this.setState(item);
};
render() {
return (
<View style={{ flex: 1, paddingTop: 20 }}>
{this.state.showSongList ? (
<SongList section={this.state.activeSection} />
) : (
<SectionList
renderItem={({ item, index }) => {
return <SectionListItem item={item} index={index} />;
}}
renderSectionHeader={({ section }) => {
return (
<SectionHeader
section={section}
updateState={this.updateState}
/>
);
}}
sections={ClusterData}
keyExtractor={(item, index) => item.name}
/>
)}
</View>
);
}
}
class SectionHeader extends Component {
render() {
return (
<View style={{ margin: 20, marginBottom: 10 }}>
<Text style={{ fontWeight: 'bold' }}>{this.props.section.title}</Text>
<TouchableOpacity
onPress={() =>
this.props.updateState({
showSongList: true,
activeSection: this.props.section,
})
}
>
<Text style={{ color: 'blue' }}> Play</Text>
</TouchableOpacity>
</View>
);
}
}
class SectionListItem extends Component {
render() {
return (
<View>
<Text style={{ margin: 5, marginLeft: 20, fontStyle: 'italic' }}>
{this.props.item.name}
</Text>
</View>
);
}
}
export class SongList extends Component {
state = {
isPlayActive: false,
};
startPlay = data => {
this.setState({
isPlayActive: true,
data: data,
});
};
render() {
return (
<View style={{ flex: 1 }}>
<FlatList
data={this.props.section.songlist}
renderItem={({ item, index, rowId }) => {
return (
<FlatListItem
item={item}
index={index}
startPlay={this.startPlay}
/>
);
}}
/>
{this.state.isPlayActive && <Play {...this.state.data} />}
</View>
);
}
}
class FlatListItem extends Component {
render() {
return (
<View style={{ backgroundColor: '#555', height: 80, marginTop: 20 }}>
<TouchableOpacity
onPress={() =>
this.props.startPlay({
songIndex: 0,
item: this.props.item,
})
}
>
<Text
style={{
paddingTop: 10,
textAlign: 'center',
fontSize: 20,
color: '#FFF',
}}
>
{this.props.item.title}
</Text>
<Text
style={{
textAlign: 'center',
fontSize: 15,
paddingTop: 10,
color: '#FFF',
}}
>
{this.props.item.artist}
</Text>
</TouchableOpacity>
</View>
);
}
}
export class Play extends Component {
componentDidMount() {
TrackPlayer.setupPlayer().then(async () => {
// Adds a track to the queue
await TrackPlayer.add(this.props.item);
// Starts playing it
TrackPlayer.play();
});
}
onPressPlay = () => {
TrackPlayer.play();
};
onPressPause = () => {
TrackPlayer.pause();
};
render() {
return (
<View style={{ height: 400 }}>
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity
style={{
backgroundColor: '#f0f0f0',
height: 40,
flex: 1,
alignItems: 'center',
justifyContent: 'center',
marginRight: 10,
}}
onPress={this.onPressPlay}
>
<Text
style={{
fontWeight: 'bold',
textAlign: 'center',
color: 'black',
}}
>
Play
</Text>
</TouchableOpacity>
<TouchableOpacity
style={{
flex: 1,
backgroundColor: '#f0f0f0',
height: 40,
alignItems: 'center',
justifyContent: 'center',
}}
onPress={this.onPressPause}
>
<Text
style={{
fontWeight: 'bold',
textAlign: 'center',
color: 'black',
}}
>
Pause
</Text>
</TouchableOpacity>
</View>
</View>
);
}
}

Categories