Rendering Child Component in React Native - javascript

I am using React Native and React Navigation to build a simple app.
I have got the basic structure working with stub state but I am having problem with changing state via callback and re-render.
In my screen, I have simple start button
`<View style={styles.buttonContainer}>
<TouchableOpacity
style={[myStyles.buttonStyle, { backgroundColor: color }]}
onPress={() => handlePress(button.title)}
>
<Text style={myStyles.textStyle}>{button.title}</Text>
</TouchableOpacity>
</View>`
Problem:
After I update my parent Component state, my child component does not instantly render to match the state change. I understood React will re-render all child components when parent state is changed?
Instead, I have to move back to previous screen and navigate again to my button screen to see that the button's color and text has changed correctly.
I've read about requiring a componentWillReceiveProps(nextProps) handler but I am not sure how to use it. I put a console.log('nextProps', nextProps) inside but it does not get fired.
From navigation perspective, the Root component is on index[0] and my button view is at index[3] so it's the 3rd screen from the root.
EDIT 1: Added Code
myButton screen:
export class TeamsScreen extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: `${navigation.state.params.game.name}: Select Team`,
headerTintColor: 'white',
headerStyle: {
backgroundColor: 'black',
},
headerVisible: true
})
componentWillReceiveProps(nextProps) {
console.log('nextProps', nextProps);
}
render() {
const { navigate, setParams } = this.props.navigation;
const { game, player, setGameState } = this.props.navigation.state.params;
const color = game.status === 'Start' ? 'green' : 'red';
const index = game.indexOf(player);
const status = game.status;
console.log('index', index);
console.log('status', status);
return (
<View style={styles.container}>
<View style={styles.buttonContainer}>
<TouchableOpacity
style={[myStyles.buttonStyle, { backgroundColor: color }]}
onPress={() => setGameState(index, status)}
>
<Text style={myStyles.textStyle}>{game.status}</Text>
</TouchableOpacity>
</View>
<View style={styles.buttonContainer}>
<Button
onPress={() => navigate('ChangeDriverScreen', { team, game })}
title='Change Driver'
/>
</View>
<View style={{ marginTop: 40, marginBottom: 20 }}>
<Text style={{ fontSize: 16, color: 'white', alignSelf: 'center' }}>Teams</Text>
</View>
<View style={{ height: 250 }}>
<FlatList
data={player.teams}
renderItem={({item}) =>
<View style={styles.buttonContainer}>
<Button
onPress={() => navigate('TeamSelectedStartScreen', { team: item })}
title={item.name}
/>
</View>}
keyExtractor={item => item.name}
/>
</View>
<Image
style={{ alignSelf: 'center', justifyContent: 'flex-end', height: 75, width: 250, resizeMode: 'stretch'}}
source={require('./images/icons/playerPlaceholder.png')}
/>
</View>
)}}
Then the onPress function that is called back:
setGameState = (gameIndex, status) => {
console.log('setGameState', gameIndex, status);
console.log('gameStateBefore', this.state.game);
const newGameState = this.state.game.map(t => {
console.log(this.state.game.indexOf(t));
if (this.state.game.indexOf(t) === gameIndex) {
const newStatus = status === 'Start' ? 'Stop' : 'Start';
t.status = newStatus; /*eslint no-param-reassign: "off"*/
console.log('inside if', t.status);
console.log('inside if game', t);
return t;
}
return t;
});
console.log('new Game State', newGameState);
this.setState(() => ({
game: newGameState
}));
}
So the setState method works (as re-navigating back to screen 3 shows the correct state but core question is how to get immediate re-render of screen 3 when setState is called from Screen 0.

Related

react native : How do I make the text label that will check the checkbox while press on it?

How do I make the text "BIRD" label that will check the checkbox while press on it ?
According to my example it does not work and it is not clear to me.
import CheckBox from '#react-native-community/checkbox';
function App(props) {
const isSelected = useSelector((rootState) => rootState.BitzuaDigumReducer.checkBox);
return (
<TouchableOpacity
activeOpacity={1}
style={{
flexDirection: 'row',
alignSelf: 'flex-start',
top: 20,
left: 10,
}}
>
<CheckBox
value={isSelected}
onValueChange={(value) => dispatch(setCheckBox(value))}
style={styles.checkbox}
tintColors={{ true: 'white', false: 'white' }}
/>
<Text style={styles.label}>BIRD</Text>
</TouchableOpacity>
);
}
I mocked Checkbox on this example, but please review it. It should give you a basic idea on how to toggle checkbox value by pressing the label: https://snack.expo.io/#zvona/toggle-checkbox-on-label
Core code:
const App = () => {
const [isSelected, setSelected] = useState(false);
const toggleCheckbox = () => {
setSelected(!isSelected);
// Here you can dispatch the event to state management
};
return (
<View style={styles.container}>
<Checkbox onValueChange={toggleCheckbox} selected={isSelected} />
<TouchableOpacity activeOpacity={0.8} onPress={toggleCheckbox}>
<Text style={styles.label}>{'Label'}</Text>
</TouchableOpacity>
</View>
);
};

Share state between components

I am working on a hobby gym management app, and I am puzzled by the mechanism of sharing state between three components in React-Native.
My three components are:
1. Schedule:
[...]
function Schedule() {
return (
<Stack.Navigator
initialRouteName="Monday"
screenOptions={{
headerStyle: { backgroundColor: "#f58220" },
headerTintColor: "#fff",
headerTitleStyle: { fontWeight: "bold" },
headerRight: () => <SwitchButton />,
}}
>
<Stack.Screen
name="TabStack"
component={TabStack}
options={{ title: "Aerobic Schedule" }}
/>
</Stack.Navigator>
);
}
export default Schedule;
I want the SwitchButton button in my Schedule component (1.) to alternate between DATA_AEROBIC and DATA_KIDS arrays props of the FlatList in (2.) based on the content of the listAerobic boolean variable.
2. MondayPage:
[...]
const MondayPage = () => {
const [selectedId, setSelectedId] = useState(null);
const [listAerobic, setListAerobic] = useState(true);
const renderItem = ({ item }) => {
const backgroundColor = item.id === selectedId ? "#6e3b6e" : "#f9c2ff";
return (
<Item
item={item}
onPress={() => setSelectedId(item.id)}
style={{ backgroundColor }}
/>
);
};
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1, padding: 5 }}>
<SafeAreaView style={styles.container}>
<FlatList
data={listAerobic ? DATA_AEROBIC : DATA_KIDS}
renderItem={renderItem}
keyExtractor={(item) => item.id}
extraData={selectedId}
/>
</SafeAreaView>
</View>
</SafeAreaView>
);
};
However, I don't know how to link the listAerobic boolean variable to the state of the SwitchButton component (3.) , and how to make it toggle on and off.
3. SwitchButton:
const SwitchButton = () => {
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
return (
<View style={styles.container}>
<Switch
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
ios_backgroundColor="#3e3e3e"
onValueChange={toggleSwitch}
value={isEnabled}
/>
<Text> aerobic/kids</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
marginRight: 5,
padding: 5,
}
});
export default SwitchButton;
Any guidance would be awesome! I mention I have really tried to look it up on different tutorials, but I can't seem to get the gist of it. It is my first project in React/React-Native.
Many thanks!
I think you just need 'value' to accept a prop passed into it on the switch button. Then wherever you use switch button just pass a boolean value into it from state e.g.
<SwitchButton enabled={this.state.switchEnabled}/>
As for setting state 'globally' so this.state.switchEnabled can be updated from various places / accessible all over the app you need to look into state management tools like Redux (or I hear 'React Hooks' is now a thing and preferred....)

Why is React.memo not working as expected?

Right so I have a sports app and im just displaying the fixtures for each team like so:
export const Fixtures = ({ fixtures }) => {
console.log('rendering again')
return (
<View>
<Text style={{ fontSize: 17, alignSelf: 'center', fontWeight: '700', marginBottom: 10 }}>
Gameweek Fixtures
</Text>
<View style={styles.container}>
<View>
{fixtures.map((match: any) => (
<View key={match.home} style={styles.match}>
// displaying fixtures here
</View>
))}
</View>
</View>
</View>
)
}
I'm displaying the images for the logo for each team above and I was noticing a flicker and when ever this component renders. and it renders in a top nav view. i.e. I click on the fixtures in the navbar and it shows this component.
I don't like the flicker so I'm trying to make it more performant and decided to use react.memo
I wrapped the above in React.memo like so:
export const Fixtures = React.memo(({ fixtures }) => {
console.log('rendering again')
return (
<View>
<Text style={{ fontSize: 17, alignSelf: 'center', fontWeight: '700', marginBottom: 10 }}>
Gameweek Fixtures
</Text>
<View style={styles.container}>
<View>
{fixtures.map((match: any) => (
<View key={match.home} style={styles.match}>
// displaying fixtures here
</View>
))}
</View>
</View>
</View>
)
},
(prevProps, nextProps) => {
console.log(prevProps, nextProps, 'the propss')
return true // props are not equal -> update the component)
})
but for some reason it is not logging the console.log when the component renders but it does log the line at the top that says: console.log('rendering again').
why is it not logging? and what can i do to prevent this flicker on every render? I just want to display the fixtures, instead it flashes, flickers then shows them (might be ok on first render for this but not on every subsequent one)

How to call multiple screens on one page in React Native

I have made a Home page in which there are three buttons in the header (like a tab navigator) I want something like on clicking each button a screen appears beneath the header, as shown in the image below:
Here's what I have tried:
constructor(props) {
super(props);
this.state = {
initialstate: 0, //Setting initial state for screens
};
}
render(){
return(
<View style={styles.container}>
<TouchableOpacity onPress={() => this.setState({ initialstate: 0})}>
<Image source={require('../../assets/add.png')}
resizeMode="contain"/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.setState({ cardstate: 1})}>
<Image source={require('../../assets/request.png')}
resizeMode="contain"/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.setState({ cardstate: 2})}>
<Image source={require('../../assets/send.png')}
resizeMode="contain"/>
</TouchableOpacity>
{this.state.initialstate == 0 ? ( <RequestComp/> ) : ( <TopUpComp/> ) }
//Over Here when I use the Third Screen like " : <SendComp/> " it gives me JSX error says "EXPECTED }"
</View>
Ciao, what you need seems more like a popup that appears from the bottom of the screen. I use react-native-popup-ui Toast component to do that.
Something like:
import { Root, Toast } from 'popup-ui'
...
<Root>
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<TouchableOpacity
onPress={() =>
Toast.show({
title: 'User created',
text: 'Your user was successfully created, use the app now.',
color: '#2ecc71'
})
}
>
<Text>Call Toast</Text>
</TouchableOpacity>
</View>
</Root>
And the result is:
Note: I have android and the Taost is overlapped by android navigation bar but on iOS you should see all the Toast component
you are using a ternary operator ( initial ? true : false ) which can work only for two components in your case.

React Native how to pass this.setState change to parent

I am new to React Native I am making a sample app where the user can login and register for a new account.
I have two React classes,
One is the main class index.ios.js and another class called register.js. In the index class I am saying if the variable register is true render the register screen.
In the class register.js I am trying to set the variable register to false using this.setState({register:false}) but it is not causing the re render of the parent (index.ios.js). Is the a super(state) method or something similar that I am missing ? I believe the parent state is not getting the values of the updated register variable.
Here are my classes:
Render inside index.ios.js:
render: function() {
if(this.state.register) {
return this.renderRegisterScreen();
}
else if (this.state.loggedIn) {
return this.userLoggedIn();
}
else {
return this.renderLoginScreen();
}
}
Register.js:
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TouchableHighlight,
TextInput,
} = React;
var Register = React.createClass({
render: function() {
return (
<View style={styles.container}>
<View style={styles.rafitoImage}>
<Image source={require('./logo.png')}></Image>
<Text style={styles.slogan}>Eliminate the need to wait!</Text>
</View>
<View style={styles.bottomSection}>
<View style={styles.username}>
<View style={styles.inputBorder}>
<TextInput placeholder="Username..." style={styles.usernameInput} onChangeText={(text) => this.setState({username: text})}/>
</View>
<View style={styles.inputBorder}>
<TextInput password={true} placeholder="Password..." style={styles.usernameInput} onChangeText={(text) => this.setState({password: text})}/>
</View>
<View style={styles.inputBorder}>
<TextInput password={true} placeholder="Verify Password..." style={styles.usernameInput} onChangeText={(text) => this.setState({verifyPassword: text})}/>
</View>
<View style={styles.inputBorder}>
<TextInput placeholder="Phone.." style={styles.usernameInput} onChangeText={(text) => this.setState({phone: text})}/>
</View>
<View style={styles.inputBorder}>
<TextInput placeholder="Email.." style={styles.usernameInput} onChangeText={(text) => this.setState({email: text})}/>
</View>
<TouchableHighlight style={styles.button}
underlayColor='#f1c40f' onPress={this.register}>
<Text style={styles.buttonText}>Register</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.signUp} onPress={this.resetToLogin}
underlayColor='#ffffff'>
<Text style={styles.signUpText}>Already A Member </Text>
</TouchableHighlight>
</View>
</View>
<View style={styles.copyright}>
</View>
</View>
);
},
resetToLogin: function() {
this.setState({
register: false //I want this to re render the home screen with the variable register as false
});
}
});
var styles = StyleSheet.create({
container: {
flex : 1
},
bottomSection: {
flex: 5,
flexDirection: 'row'
},
button: {
height: 36,
backgroundColor: '#32c5d2',
justifyContent: 'center',
marginTop: 20
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
signUpText: {
color: '#3598dc'
},
signUp: {
alignItems: 'flex-end',
marginTop: 10,
},
username: {
flex: 1,
padding: 5
},
rafitoImage: {
flex: 3,
justifyContent: 'center',
alignItems: 'center',
},
copyright: {
alignItems: 'center'
},
usernameInput: {
height: 36,
marginTop: 10,
marginBottom: 10,
fontSize: 18,
padding: 5
},
copyrightText: {
color: '#cccccc',
fontSize: 12
},
inputBorder: {
borderBottomWidth: 1,
borderBottomColor: '#ececec'
},
slogan: {
color: '#3598dc'
}
});
module.exports = Register;
Attempt 1
As per the answer I added this to my index.ios.js
renderRegisterScreen: function() {
return (
<Register login={this.login}/>
)
}
And I added this to my register.js
<TouchableHighlight style={styles.signUp} onPress={this.props.login}
underlayColor='#ffffff'>
<Text style={styles.signUpText}>Already A Member </Text>
</TouchableHighlight>
But for some reason it does not even go to the register screen anymore, it executes the login function as soon as the register screen renders. What am I missing now ? Please advise.
Thanks
Update
It works when I pass down registered as a property but not when I do not. I would like to understand why if someone could post that.
Thanks
You can pass the function down to the child as props, then set the state of the parent from within the child that way.
Parent Component:
var Parent = React.createClass({
getInitialState() {
return {
registered: false
}
},
register(){
console.log("logging in... ");
this.setState({
registered: true
});
},
render: function() {
return (
<View style={styles.container}>
<Child register={this.register.bind(this)} registered={this.state.registered} />
{this.state.registered && <View style={{padding:10, backgroundColor:'white', marginTop:10}}>
<Text style={{fontSize:20}}>Congratulations, you are now registered!</Text>
</View>}
</View>
);
}
});
Child Component:
var Child = React.createClass({
render: function() {
return(
<View style={{backgroundColor: 'red', paddingBottom:20, paddingTop:20 }}>
<TouchableHighlight style={{padding:20, color: 'white', backgroundColor: 'black'}} onPress={() => this.props.register() }>
{this.props.registered ? <Text style={{color: 'white'}}>registered</Text> : <Text style={{color: 'white'}}>register</Text>}
</TouchableHighlight>
</View>
)
}
})
Here is a more powerful solution. This will let the child component change any state variable in the parent.
Parent component:
render: function() {
return (
...
<Child setParentState={newState=>this.setState(newState)} />
...
);
}
// Take note of the setState()
Child component:
this.props.setParentState({registered: true})
Why my attempt was failing was because I was using
onPress={this.props.login}
It should be
onPress={()=>this.props.login}
because of that mistake my onPress function would execute as soon as the button would render. I am not sure why that happens but I know what my mistake was.
Using StackNavigator I found a soultion leveraging screenProps. Here you can pass down functions and values to your routes. App global state is managed in App. App then passes in functions and/or state to NavComponent screenProps. Each child route in StackNavigator will then have access via this.props.screenProps
This solution is working well for now. Would love some feedback, or suggestions for improving this method
class HomeScreen extends React.Component {
render() {
return (
<View>
<Text>{JSON.stringify(this.props.screenProps.awesome)}</Text>
<Button
onPress={() => this.props.screenProps.updateGlobalState("data")}
title="Update parent State"
/>
</View>
);
}
}
const NavComponent = StackNavigator({
Home: { screen: HomeScreen },
// AllOthers: { screen: AllComponentsHereMayAccessScreenProps },
});
export default class App extends React.Component {
constructor() {
super();
this.state = {
everythingIsAwesome: false,
}
}
_updateGlobalState(payload) {
console.log('updating global state: ', payload);
this.setState({everythingIsAwesome: payload});
}
render() {
return <NavComponent screenProps={{
updateGlobalState: this._updateGlobalState.bind(this),
awesome: this.state.everythingIsAwesome
}} />;
}
}

Categories