Skip to content

Instantly share code, notes, and snippets.

@phobon
Last active October 15, 2020 07:36
Show Gist options
  • Save phobon/369f63d38db853dba8801500ed0a19ea to your computer and use it in GitHub Desktop.
Save phobon/369f63d38db853dba8801500ed0a19ea to your computer and use it in GitHub Desktop.
// App.js
import { Provider } from "jotai";
import { Layout } from "./Layout";
const App = ({ children }) => {
return (
<Provider>
<Layout>
{children}
</Layout>
</Provider>
);
};
export default App;
// atoms.js
import { atom } from "jotai";
export const themeAtom = atom({ theme: "dark", fontSize: "big" });
export const Form = ({ ...props }) => {
const name = useState(null);
const address = useState(null);
const other = useState(null);
const fields = [name, address, other];
return (
<form>
{fields.map(([field, setField], index) => (
<input type="text" onChange={e => setField(e.value)} value={field} />
)}
</form>
);
};
// Layout.js
import { useAtom } from "jotai";
import { themeAtom } from "./atoms";
export const Layout = ({ children, ...props }) => {
const [{ theme, fontSize }, setTheme] = useAtom(themeAtom);
return (
<main className={`myapp__theme--${theme}`}>
<header className={`myapp__theme__fontsize--${fontSize}`}>
<h1>My app!</h1>
<button onClick={() => setTheme(t => ({ ...t, theme: t.theme === "dark" ? "light" : "dark" }))}>Toggle theme</button>
</header>
{children}
</main>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment