Change the color of Button when onFocus input - react-native

Good Morning , I tried a simple component with react-native that changes the color of my button while onFocus().I can't find how to change the color . Here is my component . Have you any ideas ?
import React, {Component} from 'react';
import {
StyleSheet,Text, View, Button,
} from 'react-native';
export default class App extends Component {
render() {
return (
<View style={styles.inputContainer}>
<TextInput
maxHeight={200}
style={styles.textInput}
ref={(r) => {
this.textInputRef = r;
}}
placeholder={'Message'}
underlineColorAndroid="transparent"
onFocus={()=>{/*Here i awant to change the color of Button }}
testID={'input'}
/>
<Button color="transparent" id="ScanButton"
onPress={() => this.setState({text: 'Placeholder Text'})}
title="Scan Barcode"
/>
</View>
)}

First Initialize your variable
constructor(props) {
super(props);
this.state = {
isFocus: false
}
}
In your TextInput add two props onFocus() and onBlur()
<TextInput
maxHeight={200}
style={styles.textInput}
ref={(r) => {
this.textInputRef = r;
}}
placeholder={'Message'}
underlineColorAndroid="transparent"
onBlur={() => this.onBlur()}
onFocus={() => this.onFocus()}
testID={'input'}
/>
add two methods in your class to change the state
onFocus() {
this.setState({
isFocus: true
})
}
onBlur() {
this.setState({
isFocus: false
})
}
and your button style will be like that
<Button
color={this.state.isFocus ? 'red' : 'green'}
id="ScanButton"
onPress={() => this.setState({text: 'Placeholder Text'})}
title="Scan Barcode"
/>

style={{color: this.props.focused ? '#8B327C' :'#3F8B99'}}
try something like this

Related

How to use the modal in the list in react native (a specific Modal for each list item)?

I made a customized list component (in React Native) which shows touchable images with some description texts.
I need each images open a specific Modal; but I don't know how!! where & how I should code the Modal??
... here is my photo list component:
export class CustomGallery extends Component {
render() {
let {list} = this.props;
return (
<View style={styles.container}>
<FlatList
numColumns={4}
data={list}
renderItem={({ item}) => (
<View style={styles.views}>
<TouchableOpacity style={styles.touch} >
<ImageBackground
style={styles.img}
source={{ uri: item.photo }}
>
<Text style={styles.txt}>{item.name}</Text>
<Text style={styles.txt}>{item.key}</Text>
<Text style={styles.txt}>{item.describtion}</Text>
</ImageBackground>
</TouchableOpacity>
</View>
)}
/>
</View>
);
}
}
For Modal you can use modal from material-ui - https://material-ui.com/components/modal/
The Modal component renders its children node infront of a backdrop component. Simple and basic example would be like a confirmation message that pops up asking whether you surely want to delete particular information or not.
From your code I am guessing you want to display information regarding the image using modal when you click on the image.
Here I have added Modal component:
import React from 'react';
import Modal from '#material-ui/core/Modal';
export class CustomGallery extends Component {
constructor() {
super();
this.state = {
modalOpen: false,
snackOpen: false,
modalDeleteOpen: false,
};
}
handleModalOpen = () => {
this.setState({ modalOpen: true });
}
handleModalClose = () => {
this.setState({ modalOpen: false });
}
render() {
let {list} = this.props;
return (
<View style={styles.container}>
<FlatList
numColumns={4}
data={list}
renderItem={({ item}) => (
<View style={styles.views}>
<TouchableOpacity style={styles.touch} >
<ImageBackground
style={styles.img}
onClick={() => this.handleModalOpen()}
>
{ item.photo }
</ImageBackground>
<Modal
open={this.state.modalOpen}
onClose={this.handleModalClose}
closeAfterTransition
>
<Text style={styles.txt}>{item.name}</Text>
<Text style={styles.txt}>{item.key}</Text>
<Text style={styles.txt}>{item.describtion}</Text>
</Modal>
</TouchableOpacity>
</View>
)}
/>
</View>
);
}
}
I am not sure about how you set the image. But anyways below method is an example of opening modal with dynamic data.
import React, {useState} from "react";
import { Button, TouchableOpacity, FlatList, Modal, Text } from "react-native";
function App() {
const [value, setValue] = useState("");
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
];
return (
<>
<FlatList
data={DATA}
renderItem={({item}) => (
<TouchableOpacity onPress={() => setValue(item.title)}>
<Text>{item.title}</Text>
</TouchableOpacity>
)}
/>
<Modal visible={value}>
<Text>{value}</Text>
<Button title="close" onPress={() => setValue("")} />
</Modal>
</>
)
}
export default App;

Getting null instead of text

I'm trying to get the text from two text fields I have.
But when I try to log the text to the console it always prints nothing, It has the LOG tag of course, but nothing else.
This is my code:
class Login extends React.Component {
state = {
email : '',
password: '',
}
handleLogin = () => {
console.log(this.state.email);
};
render() {
return(
<View style={styles.superContainer}>
<View style={styles.formContainer}>
<AppTextInput
placeHolderText="Email#Address.com"
onChangeText={(text) => this.setState({email: text})}/>
<AppTextInput
placeHolderText="Password"
onChangeText={(text) => this.setState({password: text})}/>
</View>
<View style={styles.buttonContainer}>
<AppButton
title="LOGIN"
onPress={this.handleLogin}
/>
</View>
</View>
);
}
}
I searched for an answer, but it seems like it should work. It is written just like in other answers I saw to the same question, and it is written like that on the docs I saw.
What am I doing wrong?
As request, I added an image of the console:
EDIT: I now tried to change the 'email' in the this.state part, when logging it is showing, it seems like the TextInput won't get the text on onChangeText
Try this:
import {TextInput} from 'react-native';
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: ''
};
}
handleLogin = () => {
console.log(this.state.email);
};
render() {
return(
<View style={styles.superContainer}>
<View style={styles.formContainer}>
<TextInput
placeHolderText="Email#Address.com"
onChangeText={(email) => this.setState({email})}/>
<TextInput
placeHolderText="Password"
onChangeText={(password) => this.setState({password})}/>
</View>
<View style={styles.buttonContainer}>
<AppButton
title="LOGIN"
onPress={this.handleLogin}
/>
</View>
</View>
);
}
}
I can verify that the following code is working on Snack, I have slightly modified some elements (nothing major) and used the alert, instead of console.log. You may directly paste it onto snack to view the result.
import {TextInput} from 'react-native';
import React from 'react'
import { Text, View, Button } from 'react-native';
class Login extends React.Component {
state = {
email : '',
password: '',
}
handleLogin = () => {
alert(this.state.password + " " + this.state.email);
};
render() {
return(
<View>
<View>
<TextInput
placeHolderText="Email#Address.com"
onChangeText={(text) => this.setState({email: text})}/>
<TextInput
placeHolderText="Password"
onChangeText={(text) => this.setState({ password: text })}
/>
</View>
<View >
<Button
title="LOGIN"
onPress={this.handleLogin}
/>
</View>
</View>
);
}
}
export default Login;
Finally figured it out, the problem was that I was using a custom TextInput (aka AppTextInput) and didn't pass it the onChangeText.
Adding to AppTextInput onChangeText={this.props.onChangeText} fixed the issue.
This is the full render function of AppTextInput:
render() {
const { isFocused } = this.state;
const {onFocus, onBlur, onChangeText} = this.props;
return (
<TextInput
placeholder= {this.props.placeHolderText}
selectionColor = {COLORS.appOrange}
underlineColorAndroid={
isFocused ? COLORS.appOrange : COLORS.appGray
}
onChangeText={this.props.onChangeText}
onFocus = {this.handleFocus}
onBlur = {this.handleBlur}
style = {styles.textInput}
/>
);
}

Add text dynamically to TextInput

I would like to add a UnicodeText viewed inside the textInput when I click a button.
I've tried to create a state {text} then add the UnicodeText to the state text.
The text with the added text is properly shown in the console.log(). Not in the textInput.
import { Icon, Input } from "react-native-elements";
var emoji = require("node-emoji");
export default class MainViewMessageInput extends React.Component {
constructor(props) {
super(props);
this.state = {
text: "",
username: "",
visible: false,
showEmoticons: false
};
}
_sendMessage() {
var texte = this.state.text;
this.setState({ text: "" });
console.log(this.state.text);
}
_addEmoji() {
this.state.text = this.state.text + emoji.get("green_heart");
const emojiChar = this.state.text + emoji.get("green_heart");
this.setState({ text: emojiChar });
console.log(this.state.text);
}
render() {
return (
<View style={styles.container}>
<Input
style={{ flex: 1 }}
leftIcon={
<TouchableHighlight
onPress={() => {
this._addEmoji();
}}
style={styles.icon}
>
<Icon size={40} color="#d2d3d5" name="mood" />
</TouchableHighlight>
}
rightIcon={
<Icon
reverse
onPress={() => this.setState({ visible: true })}
color="#00b5ec"
name="send"
size={23}
/>
}
rightIconContainerStyle={{ marginRight: -7 }}
leftIconContainerStyle={{ marginLeft: 0 }}
inputContainerStyle={styles.inputContainer}
inputStyle={styles.input}
placeholder="Write your message ..."
underlineColorAndroid="transparent"
multiline={true}
editable={true}
onChangeText={text => this.setState({ text })}
/>
</View>
);
}
}
Is it possible to do?
you can push textinput into array in runtime so u get textinput dynamically
for input add field value={this.state.text}
reference
remove this.state.text = this.state.text + emoji.get("green_heart"); from _addEmoji()

React Native - Access Wrapped Component Methods

I'm trying to drive focus to the second field in a form using custom input components. However, I can't seem to access the focus() or other methods of TextInput which I am extending in the custom class. I have seen some information on ref forwarding as well as implementing the focus() function within the class but have not been able to get either working yet.
Whenever I try to hit the "next" button on the keyboard, it says that focus is not a function. Any help or reference would be appreciated.
<View>
<CustomInput
onRef={ref => (this.child = ref)}
autoCapitalize={'none'}
returnKeyType={'next'}
autoCorrect={false}
onSubmitEditing={() => this.lastNameInput.focus()}
updateState={(firstName) => this.setState({firstName})}
blurOnSubmit={false}
/>
<CustomInput
onRef={ref => (this.child = ref)}
autoCapitalize={'none'}
returnKeyType={'done'}
autoCorrect={false}
updateState={(lastName) => this.setState({lastName})}
ref={(input) => { this.lastNameInput = input; }}
onSubmitEditing={(lastName) => this.setState({lastName})}
/>
</View>
export default class UserInput extends Component {
render() {
return (
<View style={styles.inputWrapper}>
<TextInput
style={styles.input}
autoCorrect={this.props.autoCorrect}
autoCapitalize={this.props.autoCapitalize}
returnKeyType={this.props.returnKeyType}
placeholderTextColor="white"
underlineColorAndroid="transparent"
onChangeText={(value) => this.props.updateState(value)}
blurOnSubmit={this.props.blurOnSubmit}
/>
</View>
);
}
}
you need to do some changes in both components. according to https://stackoverflow.com/a/49810837/2083099
import React, { Component } from 'react'
import {View,TextInput} from 'react-native';
class UserInput extends Component {
componentDidMount() {
if (this.props.onRef != null) {
this.props.onRef(this)
}
}
onSubmitEditing() {
if(this.props.onSubmitEditing){
this.props.onSubmitEditing();
}
}
focus() {
this.textInput.focus()
}
render() {
return (
<View style={{ flex: 1 }}>
<TextInput
style={{ height: 100, backgroundColor: 'pink' }}
autoCorrect={this.props.autoCorrect}
autoCapitalize={this.props.autoCapitalize}
returnKeyType={this.props.returnKeyType}
placeholderTextColor="white"
underlineColorAndroid="transparent"
onChangeText={(value) => this.props.updateState(value)}
blurOnSubmit={this.props.blurOnSubmit}
ref={input => this.textInput = input}
onSubmitEditing={this.onSubmitEditing.bind(this)}
/>
</View>
);
}
}
export default class OrderScreen extends Component {
constructor(props) {
super(props);
this.focusNextField = this.focusNextField.bind(this);
this.inputs = {};
}
focusNextField(id) {
this.inputs[id].focus();
}
render() {
return (
<View style={{ flex: 1 }}>
<UserInput
autoCapitalize={'none'}
returnKeyType={'next'}
autoCorrect={false}
updateState={(firstName) => this.setState({ firstName })}
blurOnSubmit={false}
onRef={(ref) => { this.inputs['projectName'] = ref; }}
onSubmitEditing={() => {this.focusNextField('projectDescription');}}
/>
<UserInput
onRef={(ref) => {this.inputs['projectDescription'] = ref}}
autoCapitalize={'none'}
returnKeyType={'done'}
autoCorrect={false}
updateState={(lastName) => this.setState({ lastName })}
/>
</View>
)
}
}

ReactNative TextInput Focus

I'm having a form in my application where I want the user to be able to go to the next TextInput by clicking the "Next" return button.
My Input component:
export default class Input extends Component {
focusNextField = (nextField) => {
console.log('NEXT FIELD:', nextField);
this.refs[nextField].focus();
}
render() {
var keyboardType = this.props.keyboardType || 'default';
var style = [styles.textInput, this.props.style];
if (this.props.hasError) style.push(styles.error);
return (
<View style={styles.textInputContainer}>
<TextInput
placeholder={this.props.placeholder}
onChangeText={this.props.onChangeText}
style={style}
blurOnSubmit={false}
ref={this.props.reference}
returnKeyType= {this.props.returnType}
onSubmitEditing={() => this.focusNextField(this.props.fieldRef)}
secureTextEntry={this.props.isPassword}
value={this.props.value}
keyboardType={keyboardType}
underlineColorAndroid="transparent" />
{this.props.hasError && this.props.errorMessage ? <Text style={{ color: 'red' }}>{this.props.errorMessage}</Text> : null}
</View>
);
}
}
And how it is used:
<Input onChangeText={(email) => this.setState({ email })} value={this.state.email} returnType={"next"} reference={'1'} fieldRef={'2'} keyboardType="email-address" />
<Text style={{ color: '#fff', marginTop: 10, }}>Password</Text>
<Input onChangeText={(password) => this.setState({ password })} value={this.state.password} returnType={"done"}
reference={'2'} fieldRef={'2'} isPassword={true} />
But I get the error:
undefined is not an object (evaluating _this.refs[nextField].focus)
Not sure if you are still trying to do this but for anyone else who has the problem, please do the following :
Add this code to your imports (anywhere in your imports)
import { findNodeHandle } from 'react-native';
import TextInputState from 'react-native/lib/TextInputState';
export function focusTextInput(node) {
try {
TextInputState.focusTextInput(findNodeHandle(node));
} catch(e) {
console.log("Couldn't focus text input: ", e.message)
}
};
Add the following lines to your constructor
this.focusNextField = this.focusNextField.bind(this);
this.inputs = {};
Add the following function to your class
focusNextField(id) {
this.inputs[id].focus();
}
Edit your TextInput as follow :
<TextInput
onSubmitEditing={() => {this.focusNextField('two');}}
ref={ input => {this.inputs['one'] = input;}}
/>
<TextInput
onSubmitEditing={() => {this.focusNextField('three');}}
ref={ input => {this.inputs['two'] = input;}}
/>
....
Here is the source of that answer
Worked in 0.45 for me.