Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
};```

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If I’ve understood what you’re trying to do, above where you’ve written the type for your Icon component’s props, you can separate out the string type:

type IconName = 'add' | 'check' | 'down' // etc.

interface IconProps {
  name: IconName
  size: number
  // etc.
}

And then, you can pass a type parameter to your useState call

const [name, setName] = useState<IconName>('add')
                                    ^

<Icon name={name} size={25} color={COLORS.light_gray} />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading