Skip to content

malerba118/elementos-react

Repository files navigation

elementos-react

React bindings for elementos

NPM JavaScript Style Guide

Install

npm install --save elementos-react

Please see the full documentation!

Basic Usage

Open in CodeSandbox

import React from 'react';
import { 
  Button, 
  Flex, 
  FormControl, 
  FormLabel, 
  Input,
  Stack
} from "@chakra-ui/react";
import { atom, molecule, observe } from 'elementos';
import { useConstructor, useObservable } from 'elementos-react';
import * as api from "./api";

function LoginForm(props) {
  const { 
    formEl$, 
    form$, 
    submitting$ 
  } = useConstructor(({ beforeUnmount }) => {
    const formEl$ = atom(null);
    const submitting$ = atom(false);
    const form$ = molecule({
      username: atom(""),
      password: atom(""),
      formEl$
    });

    beforeUnmount(
      // log whenever formEl changes
      observe(formEl$, (formEl) => {
        console.log(formEl)
      })
    )

    beforeUnmount(
      observe(form$, (form) => {
        console.log(form)
      })
    )
    
    return {
      formEl$,
      form$,
      submitting$
    };
  });

  const form = useObservable(form$);
  const submitting = useObservable(submitting$);

  const handleSubmit = (e) => {
    e.preventDefault();
    submitting$.actions.set(true);
    api.logIn(form).finally(() => {
      submitting$.actions.set(false);
    });
  };

  return (
    <Stack ref={formEl$.actions.set} as="form" spacing={4} onSubmit={handleSubmit}>
      <FormControl id="username">
        <FormLabel>Username</FormLabel>
        <Input
          type="text"
          value={form.username}
          onChange={(e) => {
            form$.children.username.actions.set(e.target.value);
          }}
        />
      </FormControl>
      <FormControl id="password">
        <FormLabel>Password</FormLabel>
        <Input
          type="password"
          value={form.password}
          onChange={(e) => {
            form$.children.password.actions.set(e.target.value);
          }}
        />
      </FormControl>
      <Button isLoading={submitting} type="submit">
        Submit
      </Button>
    </Stack>
  );
}

License

MIT © malerba118

Releases

No releases published

Packages

No packages published