0

i am trying to print value of variable 'str' by setting its state. My approach is When the user click the button Print the TextInput value in the Text field. I am getting the value though using console and alert but its not printing in the desired tags

Here's my code

`
var str="";

class WeatherProject extends Component{

  constructor (props) {
    super(props);
    this.state={
        From:'',
        To:''
    }

  }

 changeText=(From)=>{
   this.setState({From})

 }
 onPress = ()=>{
  str= this.state.From
 }
  render(){
return (
<View>
    <TextInput placeholder="From" id="from" style={styles.fromField} onChangeText={this.changeText} /> 
    <Button
      title={"Press"}
      color="#f194ff"
      onPress={this.onPress}
      ></Button>

      <Text>{str}</Text> //Here i need the output via variable str
      </View>

);
}
}

export default WeatherProject 

`

2
  • 1
    You can directly use <Text>{this.state.From}</Text> instead of str Commented Jan 28, 2020 at 11:00
  • @b-mohammad 's answer is correct. In short, you need to change onPress = ()=>{this.setState({To: this.state.From})} and <Text>{this.state.To}</Text> Commented Jan 28, 2020 at 12:01

3 Answers 3

2

You should put str as a state, i made a demo in snack:

check is here : demo

Sign up to request clarification or add additional context in comments.

1 Comment

You have this.state.To unused. Much better of use To instead of str.
0

Seems like the variable str is out of scope in the render function.

You could just use

      <Text>{this.state.From}</Text>

Comments

0

You are not referencing to state by just writing {str} inside Text. You should do :

<Text>{this.state.From}</Text>

hope it helps

2 Comments

But this should give me a live result. I want to handle this via variable
this.state.From is a variable which you are setting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.