overwriting react-native stylesheets styles - javascript

I have a custom react component that looks like this:
import { StyleSheet } from 'react-native';
import { Input, Item } from 'native-base';
import Icon from 'react-native-vector-icons/FontAwesome';
import { moderateScale, verticalScale } from 'react-native-size-matters';
import { styles as commonStyles } from '~/styles/RegistrationStyles';
type FieldInputProps = {
handleChange: (e: string) => undefined;
handleBlur: (e: string) => undefined;
value: string;
fieldType: string;
placeholderText?: string;
hidePasswordIcon?: string;
hidePassword?: boolean;
togglePassword?: () => void;
icon: string;
};
export const FieldInput: React.FunctionComponent<FieldInputProps> = ({
handleChange,
handleBlur,
fieldType,
placeholderText,
value,
hidePassword,
hidePasswordIcon,
togglePassword,
icon,
}) => {
return (
<Item rounded style={styles.personalListItem}>
<Icon name={icon} size={moderateScale(20)} color="green" />
<Input
autoFocus={true}
autoCapitalize="none"
style={{ fontSize: moderateScale(15) }}
placeholder={placeholderText}
keyboardType="default"
onChangeText={handleChange(fieldType)}
onBlur={handleBlur(fieldType)}
value={value}
secureTextEntry={hidePassword}
/>
{togglePassword ? (
<Icon
name={hidePasswordIcon}
onPress={togglePassword}
style={commonStyles.iconStyle}
size={moderateScale(20)}
color="green"
/>
) : null}
</Item>
);
};
const styles = StyleSheet.create({
container: {
alignItems: 'center',
backgroundColor: '#2E3331',
flex: 1,
},
personalListItem: {
width: moderateScale(320),
backgroundColor: 'white',
borderBottomColor: 'grey',
borderRadius: moderateScale(10),
height: verticalScale(50),
paddingRight: moderateScale(20),
paddingLeft: moderateScale(10),
marginVertical: moderateScale(20),
},
text: {
fontFamily: 'Roboto',
fontSize: moderateScale(20),
fontWeight: '600',
marginVertical: moderateScale(10),
color: '#17D041',
},
subtext: {
color: '#17D041',
fontSize: moderateScale(14),
},
subtextBold: {
textDecorationLine: 'underline',
color: '#17D041',
fontWeight: '600',
fontSize: moderateScale(14),
},
button: {
height: moderateScale(50),
width: moderateScale(350),
borderRadius: moderateScale(10),
justifyContent: 'center',
marginBottom: moderateScale(5),
},
buttonText: {
fontSize: moderateScale(15),
},
});
Usually when I use this component, I want to keep using this style. However, in one particular case, I want to overwrite the styles. For example, change the width or the background color of the input field etc. However, if I try to overwrite the styles, there are no changes.
<FieldInput style={styles.fieldInput}
handleChange={handleChange}
handleBlur={handleBlur}
value={values.phoneNumber}
fieldType="phoneNumber"
icon="phone"
placeholderText="49152901820"
/>
fieldInput: {
width: moderateScale(320),
backgroundColor: 'red',
},

You're not using style prop in your component. Please fix it as shown below.
export const FieldInput: React.FunctionComponent<FieldInputProps> = ({
handleChange,
handleBlur,
fieldType,
placeholderText,
value,
hidePassword,
hidePasswordIcon,
togglePassword,
icon,
style,
rounded,
}) => {
return (
<Item rounded={rounded} style={[styles.personalListItem, style]}>
/* remaining code code */
</Item>
);
};

Here you are passing the styles as a parameter, lets say you want to use it for the outer wrap, you can do it like below
<Item rounded style={[styles.personalListItem,this.props.style]}>
If a style prop is received then it will overwrite the one in personalListItem, else it will use the styles in personalListItem.
You will have to add the style to the props, also you can add separate style props for inner components and use them the same way.
If you want to have only the style that is passed you can do this
<Item rounded style={this.props.style||styles.personalListItem}>
Which will use the personalListItem if a style prop is not passed

Related

tabBarOptions not applied to project (React Native)

I am creating a small app that has a to-do list and a calendar. At the bottom is a bottom tab navigator. Everything works and is functional, however, when I try to add style: {} inside tabBarOptions it isn't being applied. Changing activeTintColor, inactiveTintColor and labelStyle works just fine.
I tried to create a stylesheet and replace everything inside tabBarOptions, but that didn't work. My main goal is to simply create a slightly larger bar along the bottom of the screen. I don't even want a crazy custom navigation bar, just slightly larger so I can make the items inside a little bigger.
MainContainer Class:
import React from 'react';
import {StyleSheet} from 'react-native';
import {NavigationContainer} from '#react-navigation/native';
import {createBottomTabNavigator} from '#react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons'
//screens
import Calendar from './screens/Calendar';
import ToDoList from './screens/ToDoList';
// Screen names
const calendarName = 'Calendar';
const ToDoListName = 'To Do List';
const Tab = createBottomTabNavigator();
export default function MainContainer() {
return (
<NavigationContainer>
<Tab.Navigator
tabBarOptions={{
activeTintColor: 'tomato',
inactiveTintColor: 'black',
labelStyle: {paddingBottom: 10, fontSize: 10},
style: {padding: 10, height: 70},
}}
initialRouteName={ToDoListName}
screenOptions={({route}) => ({
tabBarIcon: ({focused, color, size}) => {
let iconName;
let rn = route.name;
if (rn === ToDoListName) {
iconName = focused ? 'list' : 'list-outline'; //icons in package. Change later.
} else if (rn === calendarName) {
iconName = focused ? 'calendar' : 'calendar-outline'
}
return <Ionicons name={iconName} size={size} color={color}/>
},
})}>
<Tab.Screen name={ToDoListName} component={ToDoList}/>
<Tab.Screen name={calendarName} component={Calendar}/>
</Tab.Navigator>
</NavigationContainer>
)
}
For reference here is my ToDoList class
import { KeyboardAvoidingView, StyleSheet, Text, View, TextInput, TouchableOpacity, Platform, Keyboard } from 'react-native';
import Task from '../../components/Task';
import React, { useState } from 'react';
import { ScrollView } from 'react-native-web';
export default function ToDoList() {
const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);
const handleAddTask = () => {
Keyboard.dismiss();
setTaskItems([...taskItems, task])
setTask(null);
}
const completeTask = (index) => {
let itemsCopy = [...taskItems];
itemsCopy.splice(index, 1);
setTaskItems(itemsCopy)
}
return (
<View style={styles.container}>
{/* Scroll View when list gets longer than page */}
<ScrollView contentContainerStyle={{
flexGrow: 1
}} keyboardShouldPersistTaps='handled'>
{/*Today's Tasks */}
<View style={styles.tasksWrapper}>
<Text style={styles.sectionTitle}>Today's Tasks</Text>
<View style={styles.items}>
{/* This is where the tasks will go*/}
{
taskItems.map((item, index) => {
return (
<TouchableOpacity key={index} onPress={() => completeTask(index)}>
<Task text={item} />
</TouchableOpacity>
)
})
}
</View>
</View>
</ScrollView>
{/* Write a task section */}
{/* Uses a keyboard avoiding view which ensures the keyboard does not cover the items on screen */}
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.writeTaskWrapper}>
<TextInput style={styles.input} placeholder={'Write a task'} value={task} onChangeText={text => setTask(text)} />
<TouchableOpacity onPress={() => handleAddTask()}>
<View style={styles.addWrapper}>
<Text style={styles.addText}>+</Text>
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#E8EAED',
},
tasksWrapper: {
paddingTop: 20,
paddingHorizontal: 20,
},
sectionTitle: {
fontSize: 24,
fontWeight: 'bold',
},
items: {
marginTop: 30,
},
writeTaskWrapper: {
position: 'absolute',
bottom: 20,
paddingLeft: 10,
paddingRight: 10,
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
},
input: {
paddingVertical: 15,
width: 250,
paddingHorizontal: 15,
backgroundColor: '#FFF',
borderRadius: 60,
borderColor: '#C0C0C0',
borderWidth: 1,
},
addWrapper: {
width: 60,
height: 60,
backgroundColor: '#FFF',
borderRadius: 60,
justifyContent: 'center',
alignItems: 'center',
borderColor: '#C0C0C0',
borderWidth: 1,
},
addText: {
},
});
And my Calendar class
import * as React from 'react';
import { View, Text } from 'react-native';
export default function Calendar(){
return(
<View>
<Text>Calendar Will go here</Text>
</View>
)
}
I made a Task component for the ToDoList. Not sure if you need it to solve this but I'll paste it here anyway.
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { TouchableOpacity } from 'react-native-web';
const Task = (props) => {
return (
<View style={styles.item}>
<View style={styles.itemLeft}>
<View style={styles.square}></View>
<Text style={styles.itemText}>{props.text}</Text>
</View>
<View style={styles.circular}></View>
</View>
)
}
const styles = StyleSheet.create({
item: {
backgroundColor: '#FFF',
padding: 15,
borderRadius: 10,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: 20,
},
itemLeft: {
flexDirection: 'row',
alignItems: 'center',
flexWrap: 'wrap',
},
square: {
width: 24,
height: 24,
backgroundColor: '#55BCF6',
opacity: .4,
borderRadius: 5,
marginRight: 15,
},
itemText: {
maxWidth: '80%',
},
circular: {
width: 12,
height: 12,
borderColor: '#55BCF6',
borderWidth: 2,
borderRadius: 5
},
});
export default Task;
It sounds like you are looking for the tabBarStyle property. You should be able to rename style (which is not a supported prop of the tab navigator) to tabBarStyle.
Here's the spot in the docs that mentions this. https://reactnavigation.org/docs/bottom-tab-navigator#tabbarstyle
What I ended up doing to solve this was to put the styling inside the screenOptions. I didn't want to do this because I wanted to separate the styling from the logic, but it solved the problem for me. See code below:
export default function MainContainer() {
return (
<NavigationContainer>
<Tab.Navigator
initialRouteName={ToDoListName}
screenOptions={({route}) => ({
tabBarIcon: ({focused, color, size}) => {
let iconName;
let rn = route.name;
if (rn === ToDoListName) {
iconName = focused ? 'list' : 'list-outline'; //icons in package. Change later.
} else if (rn === calendarName) {
iconName = focused ? 'calendar' : 'calendar-outline'
}
return <Ionicons name={iconName} size={size} color={color}/>
},
activeTintColor: 'tomato',
inactiveTintColor: 'black',
tabBarShowLabel: false,
tabBarStyle: {padding: 10, height: 100, backgroundColor: 'black'},
})}>
<Tab.Screen name={ToDoListName} component={ToDoList}/>
<Tab.Screen name={calendarName} component={Calendar}/>
</Tab.Navigator>
</NavigationContainer>
)
}

When putting new value into an input field erases a previous one

With my current code, I have two input fields and a drop down menu. When ever a value is placed into the field or modified, it clears the rest of the fields. The only one that will stay consistent is the drop down menu. I have suspicions that my useEffect hooks may be doing something, but I'm quite unsure of why. Any suggestions would be great.
(FYI: storeArtic is the push to firebase)
CustomScreen.js
import React, { useState } from "react";
import { StyleSheet, Text, Keyboard, View, TouchableWithoutFeedback } from "react-native";
import { Button, Input } from "react-native-elements";
import { Dropdown } from "react-native-material-dropdown";
import { storeArtic } from '../helpers/fb-settings';
const CustomScreen = ({ route, navigation }) =>{
//create a screen with the ability to add a picture with text to the deck of artic cards
//add check box solution for selection of word type (maybe bubbles, ask about this)
const articDrop = [
{value: 'CV'},
{value: 'VC'},
{value: 'VV'},
{value: 'VCV'},
{value: 'CVCV'},
{value: 'C1V1C1V2'},
{value: 'C1V1C2V2'},
];
const [articCard, setCard] = useState({
word: '',
imageUrl: '',
aType:'',
cType: '',
mastery: false
})
return(
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View>
<Text>Please enter the information of your custom card!</Text>
<Input
placeholder="Enter valid image url"
value={articCard.imageUrl}
autoCorrect={false}
onChangeText={(val) => setCard({ imageUrl: val })}
/>
<Input
placeholder="Enter word or phrase"
value={articCard.word}
autoCorrect={false}
onChangeText={(val) =>
setCard({ word: val, aType: val.charAt(0).toUpperCase(), mastery: false})
}
/>
<Dropdown
value={articCard.cType}
onChangeText={(text) => setCard({cType: text})}
label="Artic Type"
data={articDrop}
/>
<Button
//this will save the cards to the database
title="Save"
onPress={() => {
storeArtic({articCard})
}}
/>
<Button
title="Clear"
onPress={() => {
setCard({word: '', aType: '', cType: '', imageUrl: '', mastery: false});
navigation.navigate('Home');
}}
/>
</View>
</TouchableWithoutFeedback>
)
}
export default CustomScreen;
HomeScreen.js
import React, { useState, useEffect } from "react";
import { StyleSheet, Text, Keyboard, TouchableOpacity, View, TouchableWithoutFeedback, Image } from "react-native";
import { Button } from "react-native-elements";
import { Feather } from "#expo/vector-icons";
import { initArticDB, setupArticListener } from '../helpers/fb-settings';
const HomeScreen = ({route, navigation}) => {
const [ initialDeck, setInitialDeck] = useState([]);
useEffect(() => {
try {
initArticDB();
} catch (err) {
console.log(err);
}
setupArticListener((items) => {
setInitialDeck(items);
});
}, []);
useEffect(() => {
if(route.params?.articCard){
setCard({imageUrl: state.imageUrl, word: state.word, aType: state.aType, cType: state.cType, mastery: state.mastery})
}
}, [route.params?.articType] );
navigation.setOptions({
headerRight: () => (
<TouchableOpacity
onPress={() =>
navigation.navigate('Settings')
}
>
<Feather
style={styles.headerButton}
name="settings"
size={24}
color="#fff"
/>
</TouchableOpacity>
),
headerLeft: () => (
<TouchableOpacity
onPress={() =>
navigation.navigate('About')
}
>
<Text style={styles.headerButton}> About </Text>
</TouchableOpacity>
),
});
return(
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.container}>
<Text style={styles.textmenu}>Welcome to Artic Cards</Text>
<Text style={styles.textsubmenu}>Press Start to Begin!</Text>
<Image source={require('../assets/5-snowflake-png-image.png')}
style={{width: 300, height: 300, alignSelf: 'center'}}/>
<Button
title="Start"
style={styles.buttons}
onPress={() => navigation.navigate('Cards',
{passDeck: initialDeck})}
/>
<Button
title="Progress"
style={styles.buttons}
onPress={() => navigation.navigate('Progress')}
/>
<Button
title="Customize"
style={styles.buttons}
onPress={() => navigation.navigate('Customize')}
/>
</View>
</TouchableWithoutFeedback>
);
};
const styles = StyleSheet.create({
container: {
padding: 10,
backgroundColor: '#E8EAF6',
flex: 1,
justifyContent: 'center'
},
textmenu: {
textAlign: 'center',
fontSize: 30
},
textsubmenu:{
textAlign: 'center',
fontSize: 15
},
headerButton: {
color: '#fff',
fontWeight: 'bold',
margin: 10,
},
buttons: {
padding: 10,
},
inputError: {
color: 'red',
},
input: {
padding: 10,
},
resultsGrid: {
borderColor: '#000',
borderWidth: 1,
},
resultsRow: {
flexDirection: 'row',
borderColor: '#000',
borderBottomWidth: 1,
},
resultsLabelContainer: {
borderRightWidth: 1,
borderRightColor: '#000',
flex: 1,
},
resultsLabelText: {
fontWeight: 'bold',
fontSize: 20,
padding: 10,
},
resultsValueText: {
fontWeight: 'bold',
fontSize: 20,
flex: 1,
padding: 10,
},
});
export default HomeScreen;
Unlike class based setState, with functional components when you do setState, it will override the state with what you provide inside setState function. It is our responsibility to amend state (not overrite)
So, if your state is an object, use callback approach and spread previous state and then update new state.
Like this
<Input
placeholder="Enter valid image url"
value={articCard.imageUrl}
autoCorrect={false}
onChangeText={(val) => setCard(prev => ({ ...prev, imageUrl: val }))} //<----- like this
/>
Do the same for all your inputs.

User input validation is not working correctly

I am trying to make a component in my ReactNative app in which user can give only numbers as input, but my JavaScript reg expression is not working correctly. I used React Native hooks to manage states. I am trying to validate user input for only numbers, but input text field also replacing the numbers with empty string. The code of the component is follwoing;
import React, { useState } from 'react';
import { StyleSheet, Text, View, TextInput, Button, TouchableOpacity } from 'react-native';
import Card from '../components/Card';
import Colors from '../constants/Colors';
import Input from '../components/Input';
const StartGameScreen = props => {
const [enteredValue, setEnteredValue] = useState ('');
const numberInputHandler = inputText => {
setEnteredValue (inputText.replace(/[^0-9]/g, ''));
};
return (
<View style={styles.screen}>
<Text style={styles.title}>Start a New Game</Text>
<Card style={styles.inputContainer}>
<Text>Select a Number</Text>
<Input style={styles.inputText}
blurOnSubmit
auotCaptalize={'none'}
autoCorrect={false}
maxLength={2}
keyboardType={'number-pad'}
onChnageText={numberInputHandler}
value={enteredValue}
/>
<View style={styles.buttonContainer}>
<TouchableOpacity activeOpacity={0.4} style={{backgroundColor: Colors.accent, ...styles.button}}>
<Text style={styles.buttonText}>Reset</Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity={0.4} style={{backgroundColor: Colors.primary, ...styles.button}}>
<Text style={styles.buttonText}>Confirm</Text>
</TouchableOpacity>
</View>
</Card>
</View>
);
}
const styles = StyleSheet.create({
screen: {
flex: 1,
padding: 10,
alignItems: 'center'
},
button: {
borderRadius: 8,
justifyContent: 'center',
alignItems: 'center',
height: 35,
width: 80
},
buttonText: {
color: 'white'
},
title: {
fontSize: 20,
marginVertical: 10
},
inputContainer: {
padding: 10,
width: 300,
height: 120,
maxWidth: '80%'
},
inputText: {
width: 35,
textAlign: "center",
},
buttonContainer: {
height: 30,
flexDirection: 'row',
width: '100%',
justifyContent: 'space-between',
paddingHorizontal: 15,
alignItems: "center"
}
});
export default StartGameScreen;
The code for the input component is following;
import React from 'react';
import { TextInput, StyleSheet} from 'react-native';
const Input = props => {
return (
<TextInput {...props} style={{...styles.input, ...props.style}}/>
);
}
const styles = StyleSheet.create({
input: {
height: 30,
borderBottomWidth: 1,
borderBottomColor: 'grey',
marginVertical: 10
}
});
export default Input;
You've misspelled the prop in your implementation of Input on your StartGameScreen component which is responsible for handling the change.
onChnageText should be onChangeText
The reason your non numbers are "replaced" as well is actually because the change handler isn't mapped to onChangeText due to that typo.
Extra Note:
You've also made another typo in your Input implementation.
auotCaptalize should be autoCapitalize
There are two spelling errors:
auotCaptalize={'none'} should be autoCapitalize={'none'}, and onChnageText={numberInputHandler} should be onChangeText={numberInputHandler}

Button & Title Design on Login Page

I am creating a simple login page in react native and am facing some confusions in styling. How can I make the text on the button in the center?
How can I take the INSTARIDE text upwards and not so close to the username field. Code could be run on Expo Snack.
import React, { Component } from 'react';
import { Alert, Button, Text, Container, Header, Content, TextInput, Form, Item, View, Label, StyleSheet } from 'react-native';
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
};
}
onLogin() {
const { username, password } = this.state;
Alert.alert('Credentials', `${username} + ${password}`);
}
render() {
return (
<View style={styles.container}>
<Text style={{fontWeight: 'bold'}}>
My App
</Text>
<TextInput
value={this.state.username}
onChangeText={(username) => this.setState({ username })}
placeholder={'Username'}
style={styles.input}
/>
<TextInput
value={this.state.password}
onChangeText={(password) => this.setState({ password })}
placeholder={'Password'}
secureTextEntry={true}
style={styles.input}
/>
<Button rounded success
title={'Login!'}
style={styles.input}
color = '#65c756'
onPress={this.onLogin.bind(this)}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#1b1c1c',
},
input: {
width: 200,
height: 33,
padding: 10,
borderWidth: 1,
borderColor: 'black',
marginBottom: 10,
},
});
Check this below code
import React, { Component } from 'react';
import { Alert, Button, Text, TextInput, View, StyleSheet } from 'react-native';
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
};
}
onLogin() {
const { username, password } = this.state;
Alert.alert('Credentials', `${username} + ${password}`);
}
render() {
return (
<View style={styles.container}>
<Text style={styles.textStyle}>My App</Text>
<TextInput
value={this.state.username}
onChangeText={username => this.setState({ username })}
placeholder={'Username'}
style={styles.input}
/>
<TextInput
value={this.state.password}
onChangeText={password => this.setState({ password })}
placeholder={'Password'}
secureTextEntry={true}
style={styles.input}
/>
<View style={styles.buttonStyle}>
<Button
rounded
success
title={'Login!'}
color="#65c756"
onPress={this.onLogin.bind(this)}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
input: {
width: '90%',
padding: 10,
borderWidth: 1,
borderColor: 'black',
marginBottom: 10,
alignSelf: 'center',
},
buttonStyle: {
width: '90%',
alignSelf: 'center',
},
textStyle: {
fontWeight: 'bold',
justifyContent: 'center',
alignSelf: 'center',
marginBottom: 30,
fontSize: 18,
},
});
Change this according to your requirement. Feel free for doubts
Create custom button by text and touchable opacity
<TouchableOpacity style={{backgroundColor:'#65c756',paddingVertical:5,paddingHorizontal: 30,borderRadius:6}} onPress={this.onLogin.bind(this)}>
<Text style={{color:'white'}}>Login!</Text>
</TouchableOpacity>
for text close to input just add some padding or margin b/w them
To center the button, try adding text-align: center; to the style prop in <Text style={{color:'white'}}>Login!</Text>

How to use ref in React Navigation header

I'm adding a search bar with button (i.e. search icon) in navigationOptions of React navigation. Now I want to send the typed text with navigate function. I don't know how to pass reference of TextInput to get its native text. Following is the code I've done so far.
static navigationOptions = ({ navigation }) => (
headerStyle: {
...
},
headerTitle: (
<View style={{ width: '100%', height: 75, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', borderRadius: 50, backgroundColor: 'white' }}>
<TextInput style={{ width: '85%', padding: 15 }}
onSubmitEditing={
(e) => (e.nativeEvent.text.length > 2) && navigation.navigate('Brands', {text: e.nativeEvent.text})
} />
<TouchableOpacity style={{ width: '15%', padding: 15 }}
onPress={() => navigation.navigate('Brands'/*, {text: HERE I WANT TO GET TEXT FROM REFERENCE}*/)}>
<Icon type='FontAwesome' name='search'
style={{ color: 'red', 20, textAlign: 'center' }} />
</TouchableOpacity>
</View>
)
)};
But as navigationOptions is static, I can't use this keyword inside it. Also I can't use state inside navigationOptions as well. So how could I use ref to get input text on button press.
EDIT
I want to get TextInput value from ref
<TextInput ref={(ref) => { this.input = ref; }} />
// OR
<TextInput ref='input' />
So that I can get its value from
this.input._lastNativeText
// OR
this.refs['input']._lastNativeText
But I cant use this keyword or state in navigationOptions because its static. How can I access the value of TextInput on button click?
send callback to navigationOptions through naviagtion prop .
set callback value in componentDidMount
componentDidMount=()=> {
this.props.navigation.setParams({
onSubmitEditing: this.onSubmitEditing,
});
}
onSubmitEditing=(event)=>{
console.log(event);
//this is avaialbel here
}
Get on SubmitEdit function from naviagttion params
static navigationOptions = ({ navigation = this.props.navigation }) => {
const onSubmitEditing = navigation.state.params.onSubmitEditing;
return {
headerTitle: (
<View style={{ width: '100%', height: 75, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', borderRadius: 50, backgroundColor: 'white' }}>
<TextInput style={{ width: '85%', padding: 15 }}
onSubmitEditing={onSubmitEditing} />
<TouchableOpacity style={{ width: '15%', padding: 15 }}
onPress={() => navigation.navigate('Brands'/*, {text: HERE I WANT TO GET TEXT FROM REFERENCE}*/)}>
<Icon type='FontAwesome' name='search'
style={{ color: 'red', size: 20, textAlign: 'center' }} />
</TouchableOpacity>
</View>
)
}
};
Just in case anybody needs this
componentDidMount(){
---
this.props.navigation.setParams({
setMenuRef: this.setMenuRef.bind(this),
});
---
}
_menu = null;
setMenuRef = ref => {
this._menu = ref;
};
onSortClick() {
this._menu.show();
}
static navigationOptions = ({navigation}){
headerRight:(
---
ref={navigation.state.params && navigation.state.params.setMenuRef}
---
)
}

Categories

Resources