'How to use the useState() with specific strings ("this" | "that")
I am trying to use the useState in React-native with TypeScript and want to use specific strings that can be used in a component. How can I do this?
I have this:
|
\/
const [getViewState, setViewState] = useState();
|
\/
<Icon name={getViewState} size={25} color={COLORS.light_gray}></Icon>
type props = {
style?: StyleProp<ImageStyle>;
name: "add" | "check" | "down" | "home" | "lock" | "right" | "search" | "settings" | "user" | "grid" | "list";
size: number;
color: string;
onPress?: Function;
};```
Solution 1:[1]
useState Accepts a Generic type.
type MyType = "str1" | "str2"
useState<MyType | null>(null)
Thus you can spicify what kind of state you want.
In your example:
const [getViewState, setViewState] = useState<"string1" | "string2">("string1")
Solution 2:[2]
const [viewState, setViewState] = useState("myDefaultStateString")
<Icon name={viewState} size={25} color={COLORS.light_gray}></Icon>
// change state
const someFunciton = () => {
setViewState("someOtherString")
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ldruskis |
| Solution 2 | Yurii H |
