How to re-render a specific component in react native using reference? - react-native

I have to clear or re-render the DatePicker input on-pressing the clear/close icon. But there has no clear option in DatePicker. So I have to re-render the specific component(DatePicker) not whole UI.
import DatePicker from 'react-native-date-ranges';
<View style={styles.row}>
<Item rounded style={styles.inputWrap}>
<Input placeholder='Customer Id' keyboardType="numeric" placeholderTextColor='rgba(0,0,0,0.4)' onChangeText={(text) => this.setState({customerCode: text})}/>
</Item>
<View style={{flex: .025}}></View>
<Item rounded style={styles.inputWrap}>
<Input placeholder='Invoice No' keyboardType="numeric" placeholderTextColor='rgba(0,0,0,0.4)' onChangeText={(text) => this.setState({invoiceNo: text})}/>
</Item>
<DatePicker
style={ {height: 36, borderRadius: 8, borderColor: "#cccccc", borderWidth: 1,} }
customStyles = { {
placeholderText:{ fontSize:14 }, // placeHolder style
headerStyle : { backgroundColor:'#007aff' }, // title container style
headerMarkTitle : { }, // title mark style
headerDateTitle: { }, // title Date style
contentInput: { fontSize:14 }, //content text container style
contentText: {fontSize:14}, //after selected text Style
} } // optional
ButtonStyle={{backgroundColor:'#007aff', borderWidth:1, borderRadius:8,marginHorizontal: 20, borderColor:'#fff'}}
ButtonTextStyle={{color: '#fff',alignSelf:'center',padding:10, fontSize: 16}}
centerAlign // optional text will align center or not
allowFontScaling = {false} // optional
markText={'Select Date'}
ButtonText='Select'
placeholder={'Ex: Apr 27, 2018 → Jul 10, 2018'}
mode={'range'}
onConfirm={(text) => {this.setState({invoiceDate: text}); console.log('invoiceDate: ', text)}}
ref = {(ref)=> this.picker = ref}
/>
<Icon style={{padding: 10, marginLeft: -30, marginTop: -2}} size={20} name={'md-close'} color={'red'} onPress={() => "Clear or rerender the DatePicker Input. There are no clear option in DatePicker. So i have to rerender"}/>
</View>
I am new in react-native. So, I need your help badly

The library you're using is missing some props to set the selected date(s).
Use https://github.com/wix/react-native-calendars instead

Related

How can I use forwardRef in functional component in react native?

I made the following screen where each label + input combo is inside a child component. When I click save (salvar) I want to inspect each component's ref to see if it has a "isInvalid" variable set to true and then paint the border red and show an error message. That means the field is required, etc.
I've tried creating a ref in the parent component like this:
export default function DiaryExam({ navigation }) {
let examNameRef = useRef();
return (
<Page type="static" title={'Avaliação'} subtitle={'Editar'}>
<FormInput ref={examNameRef} inputType="text" title={"Nome da avaliação"} value={name} setValue={setName} required />
//I'll add the other refs below later
<FormInput inputType="text" title={"Código"} value={code} setValue={setCode} maxLength={8} required/>
<FormInput inputType="number" title={"Nota máxima"} value={maxGrade} setValue={setMaxGrade} />
<FormInput inputType="number" title={"Peso"} value={weight} setValue={setWeight} required />
<FormInput inputType="date" title={"Data de Início"} value={startDate} setValue={setStartDate} />
<FormInput inputType="date" title={"Data de Fim"} value={endDate} setValue={setEndDate} />
<FormInput inputType="switch" title={"Ignorar na Fórmula"} value={ignoreFormula} setValue={setIgnoreFormula} />
<Button style={[styles.button, {}]} textStyle={styles.buttonText} title={'Salvar'} onPress={() => saveExam()} requestFeedback />
</Page>
);
In the child component I have something like this ( among other things) :
export default function FormInput ({ inputType, title, value, setValue, required, maxLength, ref }) {
return (
<View>
{(inputType === 'text' || inputType === 'number') && (
<View>
<Text ref={ref} style={[styles.fieldValue, { borderColor: requiredValidationError ? 'red' : 'grey' }]}>{value}</Text>
<Text style={[{ alignSelf: 'flex-end', backgroundColor: 'white', color: requiredValidationError ? 'red' : 'grey' }]}>{requiredValidationError? 'Campo obrigatório' : ''}</Text>
</View>
)}
</View>
)
I need to see if the 'value' variable is length === 0 if the 'required' prop is true and then set setRequiredValidationError(true) so it'll change the layout accordingly.
But all I get is the following error in the console:
[Tue Mar 09 2021 17:21:48.858] ERROR Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
I have googled react native forwardRef, but all the examples and documentations are for traditional React or they use class components and nothing I've tried works. How would I do that?
As per the warning, you need to use React.forwardRef. You can do it like this:
const FormInput = React.forwardRef(({
inputType,
title,
value,
setValue,
required,
maxLength
}, ref) => {
return (
{(inputType === 'text' || inputType === 'number') && (
<View>
<Text ref={ref} style={[styles.fieldValue, { borderColor: requiredValidationError ? 'red' : 'grey' }]}>{value}</Text>
<Text style={[{ alignSelf: 'flex-end', backgroundColor: 'white', color: requiredValidationError ? 'red' : 'grey' }]}>{requiredValidationError? 'Campo obrigatório' : ''}</Text>
</View>
)}
)
}
More info in the React doc, which uses functional component.

Change text color of TextInput in React Native Paper

How can I change text color of TextInput in React Native Paper without wrapping in PaperProvider?
Currently this works:
const theme = {
...DefaultTheme,
colors: {
...DefaultTheme.colors,
text: "orange",
}
};
<PaperProvider theme={theme}>
<TargetComponent />
</PaperProvider>
However I want to control text color through passed props from a parent component.
Strangely, passing backgroundColor works but color does not.
Removing the PaperProvider wrapping doesn't help either.
This is the relevant code in TargetComponent:
return (
<View style={styles.container}>
<TextInput
type="outlined"
style={this.props.style}
onChangeText={this.props.onChange}
label={this.props.label}
value={this.props.value || "Replace this text"}
placeholder={this.props.placeholder}
/>
</View>
)
this.props.style is:
{
color: "orange", // This does not work
backgroundColor: "transparent" // This works
},
Found a solution. But for those in the same predicament:
For some reason color is not recognized as a style prop even though others, like backgroundColor, are.
Simply pass theme as a prop to TextInput. In that theme object, assign the text color like so:
<TextInput
type="outlined"
style={{ ...styles.textInput, ...this.props.style }}
underlineColor={this.theme.colors.primary}
onChangeText={this.props.onChange}
label={this.props.label}
value={this.props.value || "Replace this text"}
placeholder={this.props.placeholder}
theme={{ colors: { text: this.props.style.color } }}
/>
Updated for functional components and React Native Paper 5.x
(also if you want label color control):
const MyFuncComponent = ({style, colors, onChange, label, value}) => {
const Label = <Text color={style.labelColor}>{label}</Text>;
<TextInput
type="outlined"
style={{ ...styles.textInput, ...style }}
underlineColor={theme.colors.primary}
onChangeText={onChange}
label={Label}
value={value || "Replace this text"}
placeholder={placeholder}
textColor={style.color}
/>
}
theme={{
colors: {
placeholder: 'white', text: 'white', primary: 'white',
underlineColor: 'transparent', background: '#003489'
}
}}
Just add this line theme={{colors: {text: 'Your Color' }}} to the <TextInput/> of React native paper.
<TextInput
placeholder= {'Some Text'}
theme={{
colors: {
text: 'white',
}
}}
<TextInput
type="outlined"
style={this.props.style}
onChangeText={this.props.onChange}
label={this.props.label}
value={this.props.value || "Replace this text"}
placeholder={this.props.placeholder}
theme={{ colors: { text: 'white' } }}
/>
just add color in --- theme={{ colors: { text: 'your_color' } }}

How to call a method of a component

I am using native-base datepicker and want to call the ShowDatePicker method from outside the component. It owuld be something like this except:
This.DatePicker doesnt exist
I dont know if that method is exposed, or how to reach it..
i think it has something to do with using refs?
Thank you!
<Content>
<Button onPress={this.DatePicker.showDatePicker}>
<DatePicker props}/>
</Content>
DatePicker source code: https://github.com/GeekyAnts/NativeBase/blob/master/src/basic/DatePicker.js
Well, if you have to ref it just like the another answer says, as follows
<Content>
<Button onPress={this.DatePicker.showDatePicker}>
<DatePicker ref={ref => this.DatePicker = ref } {...this.props}/>
</Content>
However this will not fix your issue unless DatePicker component takes a props as ref. In short, even if you do that in your component, you will not have access to the showDatePicker.
Rather trying to do so, you can do this in two way (assuming you are trying to showhide component on button click.
Option 1:
Use a prop showDatePicker which will show hide the component.
For ex,
<Content>
<Button onPress={this.setState({showHide: !this.state.showHide})}>
<DatePicker showDatePicker={this.state.showHide} {...this.props} />
</Content>
then in DatePicker use this prop to do some logic.
Or Option 2,
Use conditional operator to show hide the whole component. w
For ex,
<Content>
<Button onPress={this.setState({showHide: !this.state.showHide})}>
{this.state.showHide && <DatePicker {...this.props} />}
</Content>
Let me know if you wanted to do something else, I will update the answer.
EDIT:
Looking at your code in gist.github.com/fotoflo/13b9dcf2a078ff49abaf7dccd040e179, I figured what you are trying to do.
In short, you trying to show datepicker on click of a button. Unfortunately, this is not possible at the moment looking at Nativebase - how to show datepicker when clicking input? and the documentation https://docs.nativebase.io/Components.html#date-picker-def-headref.
If you really wanna have it, you should think about these possible solution,
Option 1: fork native-base do your manipulation and use the datepicker or even submit the PR to native-base for future use.
Option2: you can use any 3rd party library for eg: https://www.npmjs.com/package/react-native-modal-datetime-picker.
Or my favourite option 3:
import { TouchableOpacity, Text, Modal, View, Platform, DatePickerIOS, DatePickerAndroid } from 'react-native';
state = {
currentDate: date,
showiOSDatePicker: false,
chosenDate: date,
formattedDate
}
showDatePicker = async () => {
if (Platform.OS === 'ios') {
this.setState({
showiOSDatePicker: true
});
} else {
const { chosenDate, currentDate } = this.state;
try {
const {action, year, month, day} = await DatePickerAndroid.open({
date: chosenDate,
maxDate: currentDate
});
if (action !== DatePickerAndroid.dismissedAction) {
const dateSelected = new Date(year, month, day);
const formattedDate = this.getFormattedDate(dateSelected)
this.setState({chosenDate: dateSelected, formattedDate});
console.log(formattedDate)
}
} catch ({code, message}) {
console.warn('Cannot open date picker', message);
}
}
}
render() {
const { showiOSDatePicker } = this.state;
return (
<View>
{showiOSDatePicker &&
<Modal
animationType="fade"
transparent
visible={showiOSDatePicker}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View
style={{
display: 'flex',
flex: 1,
justifyContent: 'center'
}}
>
<View style={{
margin: 22,
backgroundColor: 'rgba(240,240,240,1)'
}}>
<View
style={{
borderBottomColor: 'rgba(87,191,229,1)',
borderBottomWidth: 2,
display: 'flex',
justifyContent: 'center',
height: 70,
paddingRight: 20
}}
>
<Text style={{
color: 'rgba(40,176,226,1)',
fontSize: 20,
paddingLeft: 20
}}>
{formattedDate}
</Text>
</View>
<DatePickerIOS
date={chosenDate}
onDateChange={this.setDate}
maximumDate={currentDate}
mode="date"
/>
<TouchableOpacity
style={{
borderTopColor: 'rgba(220,220,220,1)',
borderTopWidth: 1,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: 50
}}
onPress={this.onCloseDatePicker}
>
<Text>
Done
</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
}
<TouchableOpacity onPress={this.showDatePicker}>
<Text>Show Date</Text>
</TouchableOpacity>
</View>
);
}
Let me know if this make sense, or I will put together a working example in https://snack.expo.io/
Cheers
you have to give a ref to DatePicker
<Content>
<Button onPress={this.DatePicker.showDatePicker}>
<DatePicker ref={ref => this.DatePicker = ref } props}/>
</Content>
I had the same problem and this was my solution:
NativeBase DatePicker:
<DatePicker
defaultDate={new Date(2018, 4, 4)}
minimumDate={new Date(2018, 1, 1)}
maximumDate={new Date(2020, 12, 31)}
locale={"es"}
timeZoneOffsetInMinutes={undefined}
modalTransparent={true}
animationType={"fade"}
androidMode={"default"}
placeHolderText="Select date"
textStyle={{ color: "green" }}
placeHolderTextStyle={{ color: "#d3d3d3" }}
onDateChange={this.setDate.bind(this)}
disabled={false}
ref={c => this._datePicker = (c) }
/>
And with this you can open the datePicker:
<Button onPress={()=>{ this._datePicker.setState({modalVisible:true})}}>
<Text>
showDatePicker
</Text>
</Button>
I hope it helps

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"

FlatListFooter can't be displayed

I want to add footer to my flatList :
i try this code :
renderFooter = () => {
return (
<View
style={{
paddingVertical: 20,
borderTopWidth: 1,
borderColor: "#CED0CE"
}}
>
<Button> This is footer </Button>
</View>
);
}
<FlatList
data={menuData}
renderItem={({item}) => <DrawerItem navigation={this.props.navigation} screenName={item.screenName} icon={item.icon} name={item.name} key={item.key} />}
ListFooterComponent ={this.renderFooter}
/>
But no footer appears when running.
Any help please
You used the component
ListFooterComponent
in right way. you need to check your render method for footer. I faced the same issue and i follow this example, and it helps me. I hope it will help you.
Simple way/hack. In the menuData array, you just add a flag (i called) to the child object to indicate that it's a last item. For eg:
If you can modify your menuData structure, added lastItem prop true to indicate that it's the last item :
const menuData = [
{name:'menu1', screenName:'screen1', icon:'../assets/icon1.png'},
{name:'menu2', screenName:'screen2', icon:'../assets/icon2.png', lastItem:true}
];
and then
renderFlatItems = ({item}) => {
const itemView = null;
if (!items.lastItem) {
itemView = <DrawerItem navigation={this.props.navigation} screenName={item.screenName} icon={item.icon} name={item.name} key={item.key} />
} else {
itemView = <View style={{padding:100}}><Button> This is footer </Button> </View>
}
return {itemView};
}
then use it in the Flatlist like so
<FlatList
data={menuData}
renderItem={this.renderFlatItems}
/>
If you want a footer that remains at the bottom of the screen "Above" the list, then you can just add a View after the FlatList.
<View>
<FlatList style={{flex: 1}} />
<View
style={{
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
height: 50,
}}
/>
</View>