What should be the type for key? if i add (key: string) i get an error that "string" cant be used to index type " active1: boolean, active2"
const [actives, setActives] = React.useState({
active1: false,
active2: false,
});
const toggle = (key) => setActives((actives) => ({ ...actives, [key]: !actives[key] }));
return (
<View>
<Button onPress={() => toggle('active1')} active={actives.active1} />
<Button onPress={() => toggle('active2')} active={actives.active2} />
</View>
);
>Solution :
You can use keyof typeof active or keyof T where T is a type you defined for that object state.
function Comp () {
const [actives, setActives] = React.useState({
active1: false,
active2: false,
});
const toggle = (key: keyof typeof actives) => setActives((actives) => ({ ...actives, [key]: !actives[key] }));
return (
<div>
<button onClick={() => toggle('active1')} disabled={!actives.active1} />
<button onClick={() => toggle('active2')} disabled={!actives.active2} />
</div>
);
}