I need to change render function and run some sub render function when a specific state given,
For example:
render() {
return (
What about switch case instead of if-else
render() {
switch (this.state.route) {
case 'loginRoute':
return (
<Login changeRoute={this.changeRoute}
changeName={this.changeName}
changeRole={this.changeRole} />
);
case 'adminRoute':
return (
<DashboardAdmin
role={this.state.role}
name={this.state.name}
changeRoute={this.changeRoute}
/>
);
default:
return <></>;
}
render() {
return (
<View style={styles.container}>
(() => {
if (this.state == 'news') {
return <Text>data</Text>
}
else
return <Text></Text>
})()
</View>
)
}
https://react-cn.github.io/react/tips/if-else-in-JSX.html
I find this way is the nicest:
{this.state.yourVariable === 'news' && <Text>{data}<Text/>}
I do like this and its working fine.
constructor() {
super();
this.state ={
status:true
}
}
render() {
return(
{ this.state.status === true ?
<TouchableHighlight onPress={()=>this.hideView()}>
<View style={styles.optionView}>
<Text>Ok Fine :)</Text>
</View>
</TouchableHighlight>
:
<Text>Ok Fine.</Text>
}
);
}
hideView(){
this.setState({
home:!this.state.status
});
}
You can't provide if-else condition in the return block, make use of ternary block, also this.state will be an object, you shouldn't be comparing it with a value, see which state value you want to check, also return returns only one element, make sure to wrap them in a View
render() {
return (
<View style={styles.container}>
{this.state.page === 'news'? <Text>data</Text>: null}
</View>
)
}
For this we can use ternary operator or if there is only one condition then "&&" operator .Like this:-
//This is for if else
render() {
return (
<View style={styles.container}>
{this.state == 'news') ?
<Text>data</Text>
: null}
</View>
)
}
//This is only for if or only for one condition
render() {
return (
<View style={styles.container}>
{this.state == 'news') &&
<Text>data</Text>
}
</View>
)
}