Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6288

React Hooks: How can I use multiple instances of my useToggle hook on one component?

$
0
0

Overview:

I've created a custom useToggle react hook and I want to use two instances in one component. A toggle for the "Privacy Policy" and a toggle for the "Terms and Conditions."

Question

How can I use the same useToggle hook to get different constants for each useToggle hook such as the following below. A solution for [isToggled, toggle] or { isToggled, toggle } works. Object destructuring is preferred if it is possible.

const privacyPolicy = [isToggled, toggle] = useToggle();const terms = [isToggled, toggle] = useToggle();<button title="Privacy Policy" onClick={privacyPolicy.toggle} /><button title="Terms & Conditions" onClick={terms.toggle} />

useToggle.ts

// Imports: Dependenciesimport { useCallback, useState } from 'react';// Imports: TypeScript Typesimport { TReactHookUseToggle } from '@jefelewis/unison-types';// React Hook: Use Toggleexport const useToggle = (initialState: boolean = false): TReactHookUseToggle => {  // React Hooks: State  const [isToggled, setIsToggled] = useState<boolean>(initialState);  // Toggle  const toggle: () => void = useCallback((): void => setIsToggled((prevState: boolean) => !prevState), []);  return [isToggled, toggle];};

Viewing all articles
Browse latest Browse all 6288

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>