react native text input with required asterisk symbol similar to material ui - react-native

Please share samples in react native
text input with required asterisk symbol similar to material ui
enter image description here

Use react-native-paper
<TextInput
label='Password '
mode='outlined'
value={this.state.text}
onChangeText={password => this.setState({ password })}
underlineColor='transparent'
theme={...}
>
More detail Here

I have used "react-native-paper": "4.9.2" below code works fine in this version.
<TextInput
mode="flat"
label={
<Text>
Label
<Text style={{color: 'red'}}> *</Text>
</Text>
}
placeholder="Type something"
/>

Or, if you prefer, create a component for that:
import React from 'react';
import { Text } from 'react-native';
export default function InputLabel({ label, style={}, required=false }) {
return (
<Text style={style}>
{label}
{required && <Text style={{ color: 'red' }}> *</Text>}
</Text>
);
}

Related

How to set the textinput box above the Keyboard while entering the input field in react native

I am using react-native TextInput component. Here I need to show the InputBox above the keyboard if the user clicks on the textInput field.
I have tried below but i am facing the issues
1. Keyboard avoiding view
a. Here it shows some empty space below the input box
b. Manually I need to scroll up the screen to see the input field which I was given in the text field
c. Input box section is hiding while placing the mouse inside the input box
2. react-native-Keyboard-aware-scroll-view
a.It shows some empty space below the input box
b.ScrollView is reset to the top of the page after I moving to the next input box
Here I set the Keyboard-aware-scroll-view inside the ScrollView component
Kindly clarify
My example code is
<SafeAreaView>
<KeyboardAvoidingView>
<ScrollView>
<Text>Name</Text>
<AutoTags
//required
suggestions={this.state.suggestedName}
handleAddition={this.handleAddition}
handleDelete={this.handleDelete}
multiline={true}
placeholder="TYPE IN"
blurOnSubmit={true}
style= {styles.style}
/>
</ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>
[https://github.com/APSL/react-native-keyboard-aware-scroll-view]
Give your TextInput a position: absolute styling and change its position using the height returned by the keyboardDidShow and keyboardDidHide events.
Here is a modification of the Keyboard example from the React Native documentation for demonstration:
import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';
class Example extends Component {
state = {
keyboardOffset: 0,
};
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
this._keyboardDidShow,
);
this.keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
this._keyboardDidHide,
);
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow(event) {
this.setState({
keyboardOffset: event.endCoordinates.height,
})
}
_keyboardDidHide() {
this.setState({
keyboardOffset: 0,
})
}
render() {
return <View style={{flex: 1}}>
<TextInput
style={{
position: 'absolute',
width: '100%',
bottom: this.state.keyboardOffset,
}}
onSubmitEditing={Keyboard.dismiss}
/>
</View>;
}
}
First of all, You don't need any extra code for Android platform. Only keep your inputs inside a ScrollView. Just use KeyboardAvoidingView to encapsulate the ScrollView for iOS platform.
Create function such as below which holds all the inputs
renderInputs = () => {
return (<ScrollView
showsVerticalScrollIndicator={false}
style={{
flex: 1,
}}
contentContainerStyle={{
flexGrow: 1,
}}>
<Text>Enter Email</Text>
<TextInput
style={styles.text}
underlineColorAndroid="transparent"
/>
</ScrollView>)
}
Then render them inside the main view as below
{Platform.OS === 'android' ? (
this.renderInputs()
) : (
<KeyboardAvoidingView behavior="padding">
{this.renderInputs()}
</KeyboardAvoidingView>
)}
I have used this method and I can assure that it works.
If it is not working then there is a chance that you are missing something.
Hooks version:
const [keyboardOffset, setKeyboardOffset] = useState(0);
const onKeyboardShow = event => setKeyboardOffset(event.endCoordinates.height);
const onKeyboardHide = () => setKeyboardOffset(0);
const keyboardDidShowListener = useRef();
const keyboardDidHideListener = useRef();
useEffect(() => {
keyboardDidShowListener.current = Keyboard.addListener('keyboardWillShow', onKeyboardShow);
keyboardDidHideListener.current = Keyboard.addListener('keyboardWillHide', onKeyboardHide);
return () => {
keyboardDidShowListener.current.remove();
keyboardDidHideListener.current.remove();
};
}, []);
You can use a scrollview and put all components inside the scrollview and add automaticallyAdjustKeyboardInsets property to scrollview.it will solve your problem.
automaticallyAdjustKeyboardInsets Controls whether the ScrollView should automatically adjust its contentInset and
scrollViewInsets when the Keyboard changes its size. The default value is false.
<ScrollView automaticallyAdjustKeyboardInsets={true}>
{allChildComponentsHere}
<View style={{ height: 30 }} />//added some extra space to last element
</ScrollView>
Hope it helps.
you can use KeyboardAvoidingView as follows
if (Platform.OS === 'ios') {
return <KeyboardAvoidingView behavior="padding">
{this.renderChatInputSection()}
</KeyboardAvoidingView>
} else {
return this.renderChatInputSection()
}
Where this.renderChatInputSection() will return the view like textinput for typing message. Hope this will help you.
For android you can set android:windowSoftInputMode="adjustResize" for Activity in AndroidManifest file, thus when the keyboard shows, your screen will resize and if you put the TextInput at the bottom of your screen, it will be keep above keyboard
react-native-keyboard-aware-scroll-view caused similar issue in ios. That's when I came across react-native-keyboard-aware-view. Snippets are pretty much same.
<KeyboardAwareView animated={true}>
<View style={{flex: 1}}>
<ScrollView style={{flex: 1}}>
<Text style={{fontSize: 20, color: '#FFFFFF'}}>A</Text>
<Text style={{fontSize: 20, color: '#FFFFFF'}}>B</Text>
<Text style={{fontSize: 20, color: '#FFFFFF'}}>C</Text>
<Text style={{fontSize: 20, color: '#FFFFFF'}}>D</Text>
</ScrollView>
</View>
<TouchableOpacity style={{height: 50, backgroundColor: 'transparent', alignItems: 'center', justifyContent: 'center', alignSelf: 'stretch'}}>
<Text style={{fontSize: 20, color: '#FFFFFF'}}>Submit</Text>
</TouchableOpacity>
</KeyboardAwareView>
Hope it hepls
You will definitely find this useful from
Keyboard aware scroll view Android issue
I really don't know why you have to add
"androidStatusBar": {
"backgroundColor": "#000000"
}
for KeyboardawareScrollview to work
Note:don't forget to restart the project without the last step it might not work
enjoy!
I faced the same problem when I was working on my side project, and I solved it after tweaking KeyboardAvoidingView somewhat.
I published my solution to npm, please give it a try and give me a feedback! Demo on iOS
Example Snippet
import React from 'react';
import { StyleSheet, TextInput } from 'react-native';
import KeyboardStickyView from 'rn-keyboard-sticky-view';
const KeyboardInput = (props) => {
const [value, setValue] = React.useState('');
return (
<KeyboardStickyView style={styles.keyboardView}>
<TextInput
value={value}
onChangeText={setValue}
onSubmitEditing={() => alert(value)}
placeholder="Write something..."
style={styles.input}
/>
</KeyboardStickyView>
);
}
const styles = StyleSheet.create({
keyboardView: { ... },
input: { ... }
});
export default KeyboardInput;
I based my solution of #basbase solution.
My issue with his solution that it makes the TextInput jumps up without any regard for my overall view.
That wasn't what I wanted in my case, so I did as he suggested but with a small modification
Just give the parent View styling like this:
<View
style={{
flex: 1,
bottom: keyboardOffset,
}}>
And it would work! the only issue is that if the keyboard is open and you scrolled down you would see the extra blank padding at the end of the screen.
android:launchMode="singleTask"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan"
write these two lines in your android/app/src/main/AndroidManifest.xml
in activity tag
flexGrow: 1 is the key.
Use it like below:
<ScrollView contentContainerStyle={styles.container}>
<TextInput
label="Note"
value={currentContact.note}
onChangeText={(text) => setAttribute("note", text)}
/>
</ScrollView>
const styles = StyleSheet.create({
container: {
flexGrow: 1,
},
});
Best and Easy Way is to use Scroll View , It will Automatically take content Up and TextInput will not be hide,Can refer Below Code
<ScrollView style={styles.container}>
<View>
<View style={styles.commonView}>
<Image source={firstNameIcon} style={{width: 25, height: 25}}></Image>
<Text style={styles.commonTxt}>First Name</Text>
</View>
<TextInput
onFocus={() => onFocus('firstName')}
placeholder="First Name"
style={styles.txtInput}
onChangeText={(text) => onChangeText(text, 'firstName')}
value={firstNameValue}
/>
</View>
<View>
<View style={styles.commonView}>
<Image source={LastNameIcon} style={{width: 25, height: 25}}></Image>
<Text style={styles.commonTxt}>Last Name</Text>
</View>
<TextInput
onFocus={() => onFocus('lastName')}
placeholder="Last Name"
style={styles.txtInput}
onChangeText={(text) => onChangeText(text, 'lastName')}
value={lastNameValue}
/>
</View>
<View>
<View style={styles.commonView}>
<Image source={callIcon} style={{width: 25, height: 25}}></Image>
<Text style={styles.commonTxt}>Number</Text>
</View>
<TextInput
onFocus={() => onFocus('number')}
placeholder="Number"
style={styles.txtInput}
onChangeText={(text) => onChangeText(text, 'number')}
value={numberValue}
/>
</View>
<View>
<View style={styles.commonView}>
<Image source={emailIcon} style={{width: 25, height: 25}}></Image>
<Text style={styles.commonTxt}>Email</Text>
</View>
<TextInput
onFocus={() => onFocus('email')}
placeholder="Email"
style={styles.txtInput}
onChangeText={(text) => onChangeText(text, 'email')}
value={emailValue}
/>
</View>
<View style={styles.viewSavebtn}>
<TouchableOpacity style={styles.btn}>
<Text style={styles.saveTxt}>Save</Text>
</TouchableOpacity>
</View>
</ScrollView>
go to your Android>app>src>main> AndroidManifest.xml
write these 2 lines :
android:launchMode="singleTop" android:windowSoftInputMode="adjustPan"

One component at the left with defined width and another one at its right taking the rest of the horizontal space

I'm trying to make an component which has two TextInput's :
Number of the street
Name of the street
I want the first one to have a width of 35 and the second one to fill the remaining space horizontally.
How would you do that ?
My code:
import React from 'react';
import {StyleSheet, View} from 'react-native';
import FormInput from "./FormInput"
export default class NoStreetInput extends React.Component {
render() {
return(
<View style={{flex:1, flexDirection: 'row'}}>
<FormInput style={{container: {width: 35}}} placeholder="N°" defaultValue="4"/>
<FormInput style={{container: {flexGrow: 1}}} placeholder="Addresse" defaultValue="Chemin Du Moulin" />
</View>
);
}
}
My FormInput component (just in case) :
<View style={styles.container}>
<TextInput
style={styles.textInput}
autoCorrect={false}
defaultValue={this.props.defaultValue}
placeholder={this.props.placeholder}
secureTextEntry={secureTextEntry}
password={password}
keyboardType={keyboardType}
/>
</View>
To do this, you will simply need to have one TextInput's width set to 35 (which you did), and the other's TextInput with its flex attribute set to 1:
<View
style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}}
>
<TextInput value="No" style={{ width: 35 }} />
<TextInput value="Street Name" style={{ flex: 1 }} />
</View>
(obviously your styling should be kept inside a StyleSheet instead, but you get the point)
Here's a working example
Actually I found out what was missing. I begin with React Native and I thought I could access my children style properties of my custom component without adding a props.
I forgot to create a props for my component so that it can take a style from outside.
I finally made it like that :
style={{..}} is now a props in my custom component (see 2nd code)
export default class NoStreetInput extends React.Component {
render() {
return(
<View style={{flex:1, flexDirection: 'row'}}>
<FormInput style={{flex:0, width:35}} placeholder={this.props.placeholderNo}
defaultValue={this.props.defaultValueNo} width="35" keyboardType="number-pad" upperLabel="No"/>
<FormInput style={{flex:1}} placeholder={this.props.placeholderStree}
defaultValue={this.props.defaultValueStreet} upperLabel="Rue" />
</View>
);
}
}
My custom component (it's a bit different than before but the logic is the same) :
<View style={[styles.container, this.props.style]}>
<Text style={[styles.upperLabel, customStyle]}>{upperLabel}</Text>
<TextInput
style={[styles.textInput, this.props.textInputStyle]}
autoCorrect={false}
defaultValue={this.props.defaultValue}
value={text}
placeholder={this.props.placeholder}
secureTextEntry={secureTextEntry}
password={password}
keyboardType={keyboardType}
maxLength={maxLength}
onChangeText={this.handleChangeText}
onSubmitEditing={this.handleSubmitEditing}
/>
</View>
style={[styles.textInput, this.props.textInputStyle]} allows me to have a default style for my component, which can be overriden by this.props.textInputStyle :)

Button in TextInput in react native

How can I insert and style a button in text input in react native like this:
Can I use any code like this?
<Textinput>
<Button></Button>
</Textinput>
Sorry for the delay, but something like this should work:
<View style={{flexDirection:'row', width: window.width, margin: 10, padding:4, alignItems:'center', justifyContent:'center', borderWidth:4, borderColor:'#888, borderRadius:10, backgroundColor:'#fff'}}>
<View style={{flex:4}}>
<TextInput
onChangeText = {(textEntry) => {this.setState({searchText: textEntry})}}
style={{backgroundColor:'transparent'}}
onSubmitEditing = {()=>{this.onSubmit(this.state.searchText)}}
/>
</View>
<View style={{flex:1}}>
<Button onPress={ () => this.onSubmit(this.state.searchText) }>
<Image source={ require('../images/searchImage.png') } style={ { width: 50, height: 50 } } />
</Button>
</View>
</View>
where you adjust the size based on your image and Button is imported like:
import Button from '../components/Button';
I like to keep the button in an external folder, where it is like:
import React, { Component } from 'react';
import { Text, TouchableOpacity } from 'react-native';
class Button extends Component {
handlePress(e) {
if (this.props.onPress) {
this.props.onPress(e);
}
}
render() {
return (
<TouchableOpacity
onPress={ this.handlePress.bind(this) }
style={ this.props.style } >
<Text>{ this.props.children }</Text>
</TouchableOpacity>
);
}
}
export default Button;
Good luck!
wrapping both in a View with flexDirection:row should get you there.
If you want to get more advanced, you could look at the react-native-textinput-effects package that will give you some very nicely styled inputs.
<View style={{flexDirection:'row'}}>
<View>
<TextInput
style={{alignItems:'center',justifyContent:'center',backgroundColor:'white'}}
value = {this.state.searchString}
onChangeText = {(searchString) => {this.setState({searchString})}}
placeholder = 'Search'
keyboardType = 'web-search'
onSubmitEditing = {()=>{this._fetchResults()}}
ref = 'searchBar'
/>
</View>
<TouchableHighlight style={{alignItems:'center',justifyContent:'center'}} onPress = {()=>{this._fetchResults()}} underlayColor = 'transparent'>
<View>
<Icon name="search" size = {20} color = "#4285F4" />
</View>
</TouchableHighlight>
</View>
if you are not using react-native-vector-icons replace icon with .png magnifying glass image

How to use TouchableNativeFeedback in React native android?

I am getting warnings while using this component. Trying to use this component as a button. I tried require('TouchableNativeFeedback') but no use. I also tried to npm install TouchableNativeFeedback, but failed. How should it be incorporated in my react native android code?
{
var TouchableNativeFeedback= require('TouchableNativeFeedback');
var Button= require('react-native-button');
var {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TouchableNativeFeedback,
} = React;
var AwesomeProject = React.createClass({
render: function() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
My first App
</Text>
<Text style={styles.instructions}>
we should get started
</Text>
<Text style={styles.instructions}>
Nice!!
</Text>
<Image source={require('./abc.png')} style={styles.img} >
<Text style={styles.welcome}> Inside an image! </Text>
</Image>
<TouchableNativeFeedback
style={styles.img} >
<View>
<Text style= {styles.instructions}>
Button!
</Text>
</View>
</ TouchableNativeFeedback>
<Button style={styles.img} onClick="this.butclick">
<View>
<Text style={styles.instructions}>
This is a Button
</Text>
</View>
</Button>
</View>
);
}
});
}
It can be implement like this, see the react-native documentation for more functionality.
​ <TouchableNativeFeedback
background={TouchableNativeFeedback.Ripple('red')}>
<View style={styles.view}>
<Text style={style.text}>Text Here</Text>
</View>
</TouchableNativeFeedback>
best practice to use TouchableNativeFeedback.Ripple is to check the api version of devices first, because this background type is available on Android API level 21+.
import { Platform } from 'react-native';
<TouchableNativeFeedback
onPress={this.follow}
background={
Platform.Version >= 21 ?
TouchableNativeFeedback.Ripple('rgba(0,0,0,.2)', true) :
TouchableNativeFeedback.SelectableBackground()
}
>
require isn't necessary.
TouchableNativeFeedback is like Text, Image or View.
var Button= require('react-native-button');
var {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TouchableNativeFeedback,
} = React;
var AwesomeProject = React.createClass({
render: function() {
return (
<View style={styles.container}>
<TouchableNativeFeedback
style={styles.img} >
<View>
<Text style= {styles.instructions}>
Button!
</Text>
</View>
</ TouchableNativeFeedback>
</View>
);
}
});
Firstly, you need to import the respective dependency(TouchableNativeFeedback):
import { TouchableNativeFeedback, View, Text } from 'react-native';
After this, you can use it as:
<TouchableNativeFeedback onPress={() => this._onPressButton()} key={index}>
<View>
<Text>Click Me</Text>
</View>
</TouchableNativeFeedback>
Note: Make sure to add the respective click function(this._onPressButton()) in your code, otherwise you will get an error.

React Native clear text multiple TextInput boxes

I found example code on a facebook React Native page which shows how to use setNativeProp to clear text on a click but I can't see how to do it with multiple text boxes. Here is the code:
var App = React.createClass({
clearText() {
this._textInput.setNativeProps({text: ''});
},
render() {
return (
<View style={styles.container}>
<TextInput ref={component => this._textInput = component}
style={styles.textInput} />
<TouchableOpacity onPress={this.clearText}>
<Text>Clear text</Text>
</TouchableOpacity>
</View>
);
}
});
The ref seems to be fixed in the function so will always target the same TextInput box. How can I alter the function to target any TextInput box I indicate?
This should work. Notice that the ref on the TextInput needs to be the one you call from the clearText functino.
var App = React.createClass({
clearText(fieldName) {
this.refs[fieldName].setNativeProps({text: ''});
},
render() {
return (
<View style={styles.container}>
<TextInput ref={'textInput1'} style={styles.textInput} />
<TouchableOpacity onPress={() => this.clearText('textInput1')}>
<Text>Clear text</Text>
</TouchableOpacity>
<TextInput ref={'textInput2'} style={styles.textInput} />
<TouchableOpacity onPress={() => this.clearText('textInput2')}>
<Text>Clear text</Text>
</TouchableOpacity>
</View>
);
}
});
Updated my answer to clear different fields.
You can also use something like this to clear the text of TextInput.
clearText(fieldName) {
this.refs[fieldName].clear(0);
},