Reputation: 495
I would like to know if there is an easy way to render dynamicly components into a view depending on a condition, like "userpermission='admin', which then shows more buttons that a user has without this var. something like this:
import React, { useState } from 'react';
import {Button, Text, View, StyleSheet, TouchableOpacity} from 'react-native';
const HomeScreen = ({ navigation }) => {
const userpermission = 'admin';
const adminbutton = '<Button title="Adminstuff"></Button>';
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Applikationen</Text>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('Arbeitszeiterfassung')}>
<Text style={styles.text}>Arbeitszeiterfassung</Text>
</TouchableOpacity>
// HERE I WANT TO RENDER THE BUTTON
// if(userpermission == 'admin'){
// {adminbutton}
// }
</View>
);
};
Upvotes: 1
Views: 2457
Reputation: 474
A better way to achieve this in functional component.
import { Button } from 'react-native';
const MyButton = ({userpermission}) => {
if(userpermission == 'admin'){
return <Button title="Adminstuff"/>
}
else {
return <Button title="Userstuff"/>
}
}
const HomeScreen = () => {
const userpermission = 'admin';
return (
<View>
<View>Something</<View>
<MyButton userpermission={userpermission} />
</View>
)
}
Upvotes: 1
Reputation: 6967
Try this way
const HomeScreen = ({ navigation }) => {
const userpermission = 'admin';
const adminbutton = '<Button title="Adminstuff"></Button>';
const renderButtonsContainer = () => {
return <View>
<Button title="Adminstuff"></Button>
<Button title="Adminstuff"></Button>
.........
</View>
}
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
{userpermission == 'admin' ? renderButtonsContainer() : null }
</View>
);
};
Upvotes: 2
Reputation: 1598
You can do something like this.
import React, { useState } from 'react';
import {Button, Text, View, StyleSheet, TouchableOpacity} from 'react-native';
const HomeScreen = ({ navigation }) => {
const userpermission = 'admin';
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Applikationen</Text>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('Arbeitszeiterfassung')}>
<Text style={styles.text}>Arbeitszeiterfassung</Text>
</TouchableOpacity>
{userpermission == "admin" ? <Button title="Adminstuff" /> : null}
</View>
);
};
Upvotes: 2