React Native, render a button if condition is true - react-native

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>
);
};

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>
);
};

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>
);
};

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

Related

How can I keep a check on a radio button in react native?

I'm using a radio button from React Native Paper.
The radio button itself works fine.
But if i move to another page and check the radio button again, the check box cannot be maintained.
How can I keep a check on a radio button?
I am new to React Native.
import React from 'react';
import { StyleSheet, View, TouchableOpacity, Text } from 'react-native';
import { RadioButton } from 'react-native-paper';
import { Actions } from 'react-native-router-flux';
const category = [
{
label: '한식'
},
{
label: '분식'
},
{
label: '카페, 디저트'
}
]
export default class CategoryPage extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ''
}
}
matchingPage() {
Actions.pop();
}
render() {
return (
<View style={styles.container}>
<View style={{ flex: 9, justifyContent: 'center' }}>
<RadioButton.Group onValueChange={value => this.setState({ value })} value={this.state.value}>
{category.map((data, index) =>
<RadioButton.Item
key={index}
style={styles.radioStyle}
label={data.label}
value={data.label}
color='black' />
)}
</RadioButton.Group>
</View>
<View style={{ flex: 1, alignItems: 'center' }}>
<TouchableOpacity
style={styles.buttonStyle}
onPress={this.matchingPage}>
<Text style={styles.buttonTextStyle}>선택 완료</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
import * as React from 'react';
import { View } from 'react-native';
import { RadioButton } from 'react-native-paper';
const MyComponent = () => {
const [checked, setChecked] = React.useState('first');
return (
<View>
<RadioButton
value="first"
status={ checked === 'first' ? 'checked' : 'unchecked' }
onPress={() => setChecked('first')}
/>
<RadioButton
value="second"
status={ checked === 'second' ? 'checked' : 'unchecked' }
onPress={() => setChecked('second')}
/>
</View>
);
};
export default MyComponent;
You can do something like this
Working Example here
import * as React from 'react';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
import { RadioButton, Text } from 'react-native-paper';
const category = [
{
label: '한식',
},
{
label: '분식',
},
{
label: '카페, 디저트',
},
];
const CategoryPage = () => {
const [value, setValue] = React.useState('first');
return (
<View style={styles.container}>
<View style={{ flex: 9, justifyContent: 'center' }}>
<RadioButton.Group
onValueChange={(value) => setValue(value)}
value={value}>
{category.map((data, index) => (
<RadioButton.Item
key={index}
label={data.label}
value={data.label}
color="black"
/>
))}
</RadioButton.Group>
</View>
<View style={{ flex: 1, alignItems: 'center' }}>
<TouchableOpacity
style={styles.buttonStyle}
onPress={this.matchingPage}>
<Text style={styles.buttonTextStyle}>선택 완료</Text>
</TouchableOpacity>
</View>
</View>
);
};
export default CategoryPage;
const styles = StyleSheet.create({});

React Native useState not auto Updating?

why useState auto update? I'll press button and not showing textinput. but I can save file without change. textinput will be showing. sorry my bad english
import React, { useState,useEffect } from 'react';
import {Text, TextInput, View, Button,} from 'react-native';
const Test = ({navigation}) => {
const [textInput, settextInput] = useState([]);
useEffect(() => {
addTextInput = (key) => {
textInput.push([<TextInput style={{backgroundColor :'#7ACB4A',marginTop:10}} key={key} />]);
settextInput(textInput);
console.log(textInput);
}
},[textInput]);
return(
<View>
<Button title='+' onPress={() =>
addTextInput(textInput.length)} />
{textInput.map((value, index) => {
return value
})}
<Text>{textInput.length}</Text>
</View>
);
}
export default Test;
I have a few suggests to make your code better.
Don't change state value if not in use 'setState'.
This is false by nature and causes errors.
addTextInput = (key) => {
textInput.push([<TextInput style={{backgroundColor :'#7ACB4A',marginTop:10}} key={key} />]);
settextInput(textInput);
console.log(textInput);
}
State merely contains value, it should not contain different things. You should return TextInput in your map function.
I try rewrite your code, sorry because my english. Hope help you
code:
const [textInput, setTextInput] = React.useState(['1', '2'])
const addTextInput = (key: string) => {
const tempInput = textInput.concat([key])
setTextInput(tempInput)
}
return (
<View style={{ alignItems: 'center', justifyContent: 'center', flex: 1 }}>
<Button title="+" onPress={() => addTextInput(textInput.length.toString())} />
{textInput.map((value, index) => {
return (
<TextInput style={{ backgroundColor: '#7ACB4A', marginTop: 10, width: '70%' }} key={index + ''} />
)
})}
<Text>{textInput.length}</Text>
</View>
)
}

How to get value of text in state.when i clicked on TouchableOpacity in react-native?

How to get value of text in state.when i clicked on TouchableOpacity in react-native ?
I have gender value in text of TouchableOpacity . so I want to get value of selected gender in state when i clicked on TouchableOpacity.
So please help me how i can achieve this functionality.Thank you in advanced.
This is some part of my screen you can see below.
Create function like this
setGender=(props)={
this.setState({gender:props})
}
call this function from button onPress like this
onPress={()=>this.setGender("Male")}
onPress={()=>this.setGender("Female")
and show state value in Text
Example Codebase :
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
TextInput,
TouchableOpacity
} from "react-native";
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
gender: "",
textGender:"Male"
};
}
//Get text value
getTextValue = () => {
alert(this.state.gender);
console.log("Selected Gender is ", this.state.gender);
console.log("Selected Gender From Text ", this.state.textGender);
};
render() {
return (
<View style={styles.container}>
<TextInput
value={this.state.gender}
keyboardType="default"
onChangeText={gender => this.setState({ gender })}
/>
<Text>{this.state.textGender}</Text>
<TouchableOpacity
onPress={() => this.getTextValue()}
></TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
hope this will help you
onPress = (Male) => {
this.setState({ gender: 'Male'})
}
onPress1 = (Female) => {
this.setState({ gender: 'Female'})
}
<TouchableOpacity
style={styles.button}
onPress={this.onPress(Male)}
>
<Text> Male </Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={this.onPress1(Female)}
>
<Text> Female </Text>
</TouchableOpacity>*
Hope this will help you
import React, { Component } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
export default class Home extends Component {
state = {
value: '',
};
onChangeValue = value => {
if (value !== this.state.value) {
this.setState({
value: value,
});
}
};
render() {
return (
<View style={styles.container}>
{this.state.value.length > 0 ? (
<Text
style={{
fontSize: 40,
alignSelf: 'center',
justifyContent: 'center',
}}>
{this.state.value}
</Text>
) : (
<Text
style={{
fontSize: 40,
alignSelf: 'center',
justifyContent: 'center',
}}>
I identify as you
</Text>
)}
<Button
color="#000"
title="Male"
onPress={() => this.onChangeValue('male')}
/>
<Button title="Female" onPress={() => this.onChangeValue('female')} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignContent: 'center',
justifyContent: 'center',
},
});
Feel free for doudts.

React Native - How to use a ref to set focus to an input when clicking on text

Here's what I'm doing:
export default class myComponent extends Component {
render() {
return (
<View>
<Text onPress={() => {this.input.focus()}}>Click Me</Text>
<Input ref={input => { this.input = input}}/>
</View>
)
}
}
I am using native-base components... not sure if that is affecting this.
When I press the Text component, I get an error stating: _this2.input.focus is not a function. (In '_this2.input.focus()', '_this2.input.focus' is undefined)
I don't use native-base, but at normal it should be like this:
import * as React from 'react';
import { Text, View, StyleSheet, TextInput, Dimensions } from 'react-native';
import { Constants } from 'expo';
const { width, height } = Dimensions.get('window');
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<Text onPress={() => {this.input.focus()}}>Click Me</Text>
<TextInput style={styles.input} ref={input => { this.input = input}}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
input: {
backgroundColor: '#bbb',
width: width - 40,
height: 40,
paddingHorizontal: 10,
paddingVertical: 5,
}
});
You can see the snacks here: https://snack.expo.io/#gasparteixeira/inputfocus
In case anyone comes across this stack overflow during the Hooks Era of React and React Native.
Solution with Hooks following the React Docs https://reactjs.org/docs/hooks-reference.html#useref
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
export default class myComponent extends Component {
public textInput: TextInput | null = null;
render() {
return (
<View>
<Text onPress={() => {this.textInput.focus()}}>Click Me</Text>
<TextInput ref={input => (this.textInput = input as any)}/>
</View>
);
}
}
export default class myComponent extends Component {
render() {
return (
<View>
<Text onPress={() => {this.input.focus()}}>Click Me</Text>
<Input ref={ref => (this.textinput= ref)}/>
</View>
)
}
}
and use this:
handleTextInput = () => {
this.textinput....
};

Open a WebView after a button pressed with reactNative

I am developing a mobile app with React Native. I want to open a WebView after a button pressed. Here is my code, but its not working. The button onPress method is not working.
import React, { Component } from 'react';
import { View, StyleSheet, Button, WebView } from 'react-native';
import { Constants } from 'expo';
export default class webView extends Component {
onNavigationStateChange = navState => {
if (navState.url.indexOf('https://www.google.com') === 0) {
const regex = /#access_token=(.+)/;
const accessToken = navState.url.match(regex)[1];
console.log(accessToken);
}
};
renderContent() {
return (
<WebView
source={{
uri: '',
}}
onNavigationStateChange={this.onNavigationStateChange}
startInLoadingState
scalesPageToFit
javaScriptEnabled
style={{ flex: 1 }}
/>
);
}
render() {
return (
<View style={styles.container}>
<Button
style={styles.paragraph}
title="Login"
onPress={() => this.renderContent()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
I tried onPress={this.renderContent()} this also, but it give an exception. What can I do ?
You aren't rendering your WebView in the the render() method of the Component. Just think of render as your DOM of the webpage. You need to provide the component a place in the render component, than you can remove it or add it, see i am calling the renderContent from the render method. So whenever the state variable showWebView is true it will render the WebView You should do something like this:
import React, { Component } from 'react';
import { View, StyleSheet, Button, WebView } from 'react-native';
import { Constants } from 'expo';
export default class webView extends Component {
state={
showWebView: false
}
onNavigationStateChange = navState => {
if (navState.url.indexOf('https://www.google.com') === 0) {
const regex = /#access_token=(.+)/;
const accessToken = navState.url.match(regex)[1];
console.log(accessToken);
}
};
renderContent() {
return (
<WebView
source={{
uri: '',
}}
onNavigationStateChange={this.onNavigationStateChange}
startInLoadingState
scalesPageToFit
javaScriptEnabled
style={{ flex: 1 }}
/>
);
}
render() {
return (
<View style={styles.container}>
{ this.state.showWebView && this.renderContent() }
<Button
style={styles.paragraph}
title="Login"
onPress={() => this.setState({showWebView: true})}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
I think you must import the following
import { WebView } from 'react-native-webview'
instead of
'react'