Skip to content

Instantly share code, notes, and snippets.

@Flow11

Flow11/.tsx Secret

Last active Jun 27, 2020
Embed
What would you like to do?
Zelda BOTW Part 1: Item selection
// ItemsContext.ts
import { createContext } from "react";
type ContextProps = {
setItemSelected: React.Dispatch<React.SetStateAction<number>>;
itemSelected: number;
};
const ItemsContext = createContext<Partial<ContextProps>>({});
export default ItemsContext;
// App.tsx
const [itemSelected, setItemSelected] = useState(0);
const contextState = {
setItemSelected,
itemSelected,
};
// Component structure
<App>
<ItemsContext.Provider value={contextState}>
<ItemsGrid>
<Item>
// Item component
type Props = {
name: string;
icon: string;
value: string;
itemIndex: number;
};
const Item: React.FC<Props> = ({ name, icon, value, itemIndex }) => {
const { itemSelected, setItemSelected } = useContext(ItemsContext);
const handleClick = () => {
setItemSelected && setItemSelected(itemIndex);
};
return (
<div
onClick={handleClick}
className={cx(
{
"shadow-yellow border-zelda-softYellow border-2":
itemSelected === itemIndex,
},
"relative w-20 h-20 bg-black border border-zelda-darkGray cursor-pointer"
)}
>
<img alt={name} src={icon} />
<div className="z-0 bg-black -mx-1 -my-1 text-sm text-white absolute bottom-0 right-0 border border-zelda-darkGray px-2">
{value}
</div>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment