Reputation: 11
I am new to react native and I want to toggle text on pressing the button, but the problem is that when I press button the text changed but when I press it again nothing happen. Here is my code:
Upvotes: 1
Views: 1258
Reputation: 366
When you use react hooks, you configure the component to do things after it renders. If you declare a variable outside of a useState
hook, it will be reset on every render. This is what happens to your isTrue
variable. Read more about the rules of hooks here.
You also don't need to evaluate isTrue == true
, you can just call isTrue
, it will have the same effect.
export default function App() {
var startingText = "First text"
const [isTrue, setIsTrue] = useState(true)
const [outputText, setOutputText] = useState(startingText)
function textChange() {
setIsTrue(!isTrue)
return isTrue ? startingText : setOutputText("Text Changed")
}
return(
<View>
<Text>{outputText}</Text>
<Button title="Change Text" onPress={textChange}/>
</View>
)
}
You can simplify the code even further by removing the boolean variable and moving the logic of selecting which text value to set in the textChange
function directly using a ternary operator.
export default function App() {
var startingText = ""
const [outputText, setOutputText] = useState(startingText)
function textChange() {
setOutputText(outputText === startingText ? "Text Changed" : startingText)
}
return(
<View>
<Text>{outputText}</Text>
<Button title="Change Text" onPress={textChange}/>
</View>
)
}
Upvotes: 1
Reputation: 275
Try to change the function on:
const [tooggle, setToggle] = useState(false);
function textChange() {
setToggle(!tooggle);
return isTrue === tooggle
? setOutputText('first')
: setOutputText('second');
}
Example of toggle:
import React, { useState } from 'react';
import { Button, View, Text } from 'react-native';
const ToggleFunction = () => {
const [outPutText, setOutputText] = useState('first');
const [tooggle, setToggle] = useState(false);
function textChange() {
setToggle(!tooggle);
return tooggle ? setOutputText('first') : setOutputText('second');
}
return (
<View
style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}
>
<Text>{outPutText}</Text>
<Button title="button" onPress={textChange} />
</View>
);
};
export { ToggleFunction };
Upvotes: 1