elementos-react
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

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

Readme

Keywords

none

Package Sidebar

Install

npm i elementos-react

Weekly Downloads

2

Version

1.0.0

License

MIT

Unpacked Size

21.2 kB

Total Files

13

Last publish

Collaborators

  • malerba118