React native:how to get Text value on a button click? - react-native

I have a Text, and I want to get text value on click.
for example
click()
{
// how to get text value here
}
<Text style={{color: 'red,textAlign:'center'}} onPress={this.click.bind(this)}>
Name
</Text>

Can be done this way too...
<Text onPress={(event) => console.log(event._dispatchInstances.memoizedProps.children)} >{value}</Text>

You may use ref attribute to access Text's value.
<Text ref='myText'>This is my text</Text>
<Button onPress={()=>alert(this.refs.myText.props.children)} title='Press Me'/>

You can do maintaining the text inside the state and get the text value when button is clicked.
export default class SampleApp extends Component{
constructor(props){
super(props);
this.state = {
titleText: "Click to get text! - ",
count:1
};
}
render() {
return (
<View style={{flex:1}}>
<Text style={{color:'black'}} onPress={()=>{this.onPressTitle()}}>
{this.state.titleText}
</Text>
</View>
);
}
onPressTitle(){
alert(this.state.titleText+this.state.count);
this.setState({count:this.state.count+1});
}
}
Works fine with dynamic text.

For me, it has worked with console.log(event._dispatchInstances.memoizedProps.children[0].props.children)

Related

Get user input from input field in react similar to getElementById in react native using props

I am doing a loan calculation app and i run into the trouble since i am new to react native and previously i have been manipulating the DOM using querySelector or getElementById functions. However this does not work in react, and i am using state to store the value from the user, but i just can't seem to get it right, What am i doing wrong?
I've inserted the calculation element that is later rendered in app.js. All elements are showing up with no error, but the problem is to get user input data and then be able to use that data and do calculations.
Here is my Class
class LanKalkylElement extends React.Component {
constructor(props) {
super(props);
this.state = {
loanAmount: 20000,
loanInterest: 2.5,
loanYear: 10,
};
}
changeAmount(loanAmount) {
this.setState(() => {
return {
loanAmount: parseFloat(loanAmount),
};
});
}
changeInterest(loanInterest) {
this.setState(() => {
return {
loanInterest: parseFloat(loanInterest),
};
});
}
changeYear(loanYear) {
this.setState(() => {
return {
loanYear: parseFloat(loanYear),
};
});
}
calcButton() {
Alert.alert(this.props.loanAmount);
}
buttonHomeFunc() {
this.props.navigation.navigate('Start');
}
render() {
const {loanAmount, loanInterest, loanYear} = this.state;
return(
<View style={styles.contentStyle}>
<Text style={styles.text}> Lånebelopp </Text>
<TextInput style={styles.numericInput}
onBlur={Keyboard.dismiss}
keyboardType={'numeric'}
value={loanAmount}
onValueChange={this.changeAmount.bind(this)} />
<Text style={styles.text}> Ränta </Text>
<TextInput style={styles.numericInput}
onBlur={Keyboard.dismiss}
keyboardType={'numeric'}
value={loanInterest}
onValueChange={this.changeInterest.bind(this)} />
<Text style={styles.text}> Antal år: {String(loanYear)}</Text>
<Slider step={1}
maximumValue={15}
value={loanYear}
onValueChange={this.changeYear.bind(this)} />
<Button title='Kalkylera' onPress={() => this.calcButton()}/>
<Text style={styles.textResult}>Total summa att återbetala:</Text>
<Text style={styles.textResult}>varav räntekostnad:</Text>
<Button title='Tillbaka' onPress={() => this.buttonHomeFunc()}/>
</View>
)
}
}
export default withNavigation(LanKalkylElement);
When a user changes a value in a text input, onValueChange is called. You have bound this prop to functions that modify the state for this component.
This means the value in the text input will always match the value in the state. Therefore, if you need to access the value in a text input you would simply retrieve it from the state, like this:
const loanAmount = this.state.loanAmount;
doSomethingWithLoanAmount(loanAmount);

React Native - Function doesn't seem to be called

I have a simple app with 2 images. When I click on image1, I want to display hello on the console.
But my function doesn't write anything in the console.
I didn't use a function and called directly console.log in the 2nd image and it works.
Do you know what is wrong with my function?
(I also used makeALogHello.bind(this) but it doesn't change the behavior).
export default class App extends React.Component {
constructor(){
super();
}
makeALogHello(){
console.log("hello");
}
render() {
return (
<View>
<TouchableOpacity style ={{flex:1}}
onPress={() => {this.makeALogHello} }>
<Image style ={styles.container}
resizeMode="contain"
source={require("./images/image1.png")}/>
<Text>ImageNb1</Text>
</TouchableOpacity>
<TouchableOpacity style ={{flex:1}}
onPress={() => {console.log("hi")} }>
<Image style ={styles.container}
resizeMode="contain"
source={require("./images/image2.png")}/>
<Text>ImageNb2</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
You need to call the function in your arrow function:
onPress={() => {this.makeALogHello()} }
Or simply pass the reference to your function, without wrapping it:
onPress={this.makeALogHello}

undefined is not a function in TouchableOpacity onPress

The question is almost similar to this one :
touchableopacity onpress function undefined (is not a function) React Native
But the problem is, I am getting the error despite the fact that I have bind the function. Here is my TouchableOpacity component:
<TouchableOpacity style={styles.eachChannelViewStyle} onPress={() => this.setModalVisible(true)}>
{item.item.thumbnail ?
<Image style={styles.everyVideoChannelThumbnailStyle} source={{uri: item.item.thumbnail}} />
: <ActivityIndicator style= {styles.loadingButton} size="large" color="#0000ff" />}
<Text numberOfLines={2} style={styles.everyVideoChannelVideoNameStyle}>
{item.item.title}
</Text>
</TouchableOpacity>
And this is my setModalVisible function:
setModalVisible(visible) {
console.error(" I am in set modal section ")
this.setState({youtubeModalVisible: visible});
}
Also, I have bind the function in constructor as follows:
this.setModalVisible = this.setModalVisible.bind(this);
But, I am still getting same error that undefined is not a function. Any help regarding this error?
The render method and your custom method must be under the same scope. In code below I have demonstrated the same. I hope you will modify your code accordingly as I assume you got the gist :)
class Demo extends Component {
onButtonPress() {
console.log("click");
}
render() {
return (
<View>
<TouchableOpacity onPress={this.onButtonPress.bind(this)}>
<Text> Click Me </Text>
</TouchableOpacity >
<View>
);
}
}
Alternatively binding method in constructor will also work
class Demo extends Component {
constructor(props){
super(props);
this.onButtonPress= this.onButtonPress.bind(this);
}
onButtonPress() {
console.log("click");
}
render() {
return (
<View>
<TouchableOpacity onPress={this.onButtonPress()}>
<Text> Click Me </Text>
</TouchableOpacity >
<View>
);
}
}
I'm not sure if this will help but I write my functions this way and haven't encountered this problem.
If I were you I'd try binding the function in the place where you declare it.
setModalVisible = (visible) => {
this.setState({ youtubeModalVisible: visible });
}
If you do this, you don't have to bind in the constructor.
constructor(props) {
...
// Comment this out to see it will still bind.
// this.setModalVisible = this.setModalVisible.bind(this);
...
}
Lastly, if this function will only set the modal's state to visible, you might want to remove the argument and pass it this way.
<TouchableOpacity style={styles.eachChannelViewStyle} onPress={this.setModalVisible}>
...
</TouchableOpacity>
// Refactored function declaration would look like this
setModalVisible = () => {
this.setState({ youtubeModalVisible: true });
}

react native, TextInput setting onChangeText to function

I have the following component in which I am trying to set the onSubmitEditing function of a TextInput element to a custom function called func. I would like it to take the content of the TextInput box as input to the function. How can this be done? Below is my failed attempt at doing so:
export default class Component4 extends Component {
func(input){
// will add stuff here later
}
render(){
return (
<View style={{padding: 30}}>
<TextInput placeholder="default" onSubmitEditing=this.func/>
</View>
);
}
}
PS:
Thanks to everyone so far for the help, I've managed to get it working partly, here is my code now:
export default class Component4 extends Component {
constructor(props) {
super(props);
this.state = {thing: 'asdf'};
}
func(input){
this.state.thing = input;
// I will eventually do more complicated stuff here
}
render(){
return (
<View style={{padding: 30}}>
<TextInput placeholder="default" onSubmitEditing={this.func}/>
<Text>{this.state.thing}</Text>
</View>
);
}
}
this gives an error, I am trying to make it so that state.thing gets set to
the input. thanks
Option 1:
<View style={{padding: 30}}>
<TextInput placeholder="default" onSubmitEditing={this.func}/>
</View>
Option 2:
<View style={{padding: 30}}>
<TextInput placeholder="default" onSubmitEditing {(e)=>this.func(e.target.value)}/>
</View>
state={
text:''
}
Func(e){
text:e.target.value
}
onSubmitChange={this.func}
Don't forget to bind the func function

how to remove underline in react native material text field

I'm using react native text field component how can i remove bottom underline in textfield
this is my code
i followed this link: https://github.com/n4kz/react-native-material-textfield
constructor(props) {
super(props);
this.state = {
userName:'',
password:''
}
}
componentWillMount() {
}
componentDidMount(){
}
render() {
//let { userName } = this.state;
let { password } = this.state;
return (
<View style={{flex:1,justifyContent:'center'}}>
<View style={{flex:0.2,justifyContent:'center',flexDirection:'row'}}>
<View style={{flex:12}}></View>
<View style={{flex:76,borderWidth:1,borderColor:'black',borderRadius:5,marginBottom:13.7}}>
<TextField style={{ color: 'black',borderColor:'transparent'}}
label='Phone number'
textColor={'black'}
value={this.state.userName}
labelHeight={40}
labelPadding={8}
padding={10}
Bottom padding= {10}
Top padding={4}
//width={50}
//borderColor={'black'}
// textFocusColor={'orange'}
//underlineColorAndroid='transparent'
baseColor={"black"}
labelHeight={32}
blurOnSubmit={true}
//characterRestriction={10}
onChangeText={(data) => this.setState({ userName: data })}
/>
</View>
)
}
You can try underlineColorAndroid='rgba(0,0,0,0)'
Hope it helps
Other TextInput properties will also work
Ref: https://github.com/n4kz/react-native-material-textfield
React native material text field component (<TextField />) can also use all of the properties from text input component (<TextInput />). So, you can remove the underline border using underlineColorAndroid props. Set this prop to be transparent.
<TextField underlineColorAndroid="transparent" />
Try this: lineWidth={0} if you want to hide the default underline and if you want to hide the line after which appears after click try this: activeLineWidth={0}.
Fine, after using this library I end up with this solution:
You can use one of the props of react-native-material-textfield activeLineWidth with 0 as an argument.
underlineColor="transparent"