Categories
Shards React

React Development with the Shards React Library — Button Groups and Containers

Shards React is a useful UI library that lets us add many components easily into our React app.

In this article, we’ll look at how to use it to add components to our React app.

Button Group

We can add button groups into our React app with Shard Reacr’s ButtonGroip component:

import React from "react";
import { Button, ButtonGroup } from "shards-react";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <ButtonGroup>
        <Button>Left</Button>
        <Button>Middle</Button>
        <Button>Right</Button>
      </ButtonGroup>
    </div>
  );
}

We can change the group size with the size prop:

import React from "react";
import { Button, ButtonGroup } from "shards-react";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <ButtonGroup size="lg">
        <Button>Left</Button>
        <Button>Middle</Button>
        <Button>Right</Button>
      </ButtonGroup>
    </div>
  );
}

We can also set it to sm or leave it out.

And we can make the group vertical with the vertical prop:

import React from "react";
import { Button, ButtonGroup } from "shards-react";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <ButtonGroup vertical>
        <Button>Left</Button>
        <Button>Middle</Button>
        <Button>Right</Button>
      </ButtonGroup>
    </div>
  );
}

Button Toolbar

We can add a button toolbar with the ButtonToolbar component:

import React from "react";
import {
  Button,
  ButtonGroup,
  ButtonToolbar,
  FormInput,
  InputGroup
} from "shards-react";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <ButtonToolbar>
        <ButtonGroup size="sm">
          <Button>Create</Button>
          <Button>Edit</Button>
        </ButtonGroup>

        <InputGroup size="sm" className="ml-auto">
          <FormInput placeholder="Search..." />
        </InputGroup>
      </ButtonToolbar>
    </div>
  );
}

We can add ButtonGroup and InputGroup inside a ButtonToolbar .

Card

Cards let us add containers for content into our React app.

To add it, we write:

import React from "react";
import {
  Card,
  CardHeader,
  CardTitle,
  CardImg,
  CardBody,
  CardFooter,
  Button
} from "shards-react";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <Card style={{ maxWidth: "300px" }}>
        <CardHeader>Card header</CardHeader>
        <CardImg src="https://place-hold.it/300x200" />
        <CardBody>
          <CardTitle>Lorem Ipsum</CardTitle>
          <p>Lorem ipsum.</p>
          <Button>Read more</Button>
        </CardBody>
        <CardFooter>Card footer</CardFooter>
      </Card>
    </div>
  );
}

We add a card with various parts.

Card is the card container.

CardHeader has the card header.

CardImg has the card image.

CardBody has the card body.

CardTitle has the card title.

CardFooter has the card footer.

Container

We can use the Collapse component to toggle the visibility of our content.

For instance, we can write:

import React from "react";
import { Container, Row, Col } from "shards-react";
import "bootstrap/dist/css/bootstrap.min.css";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <Container>
        <Row>
          <Col sm="12" lg="6">
            1 / 2
          </Col>
          <Col sm="12" lg="6">
            2 / 2
          </Col>
        </Row>
      </Container>
    </div>
  );
}

to add the Container com0ponent to add a flexbox container.

Row has the rows. And Col has the columns.

We set the sm and lg props to set the column sizes for those breakpoints.

Conclusion

We can add button groups and containers into our React app with Shards React.

Categories
Shards React

React Development with the Shards React Library — Collapse, Dropdowns, and Fade Effects

Shards React is a useful UI library that lets us add many components easily into our React app.

In this article, we’ll look at how to use it to add components to our React app.

Column Order and Offset

We can set the order and offset of the columns.

For instance, we can write:

import React from "react";
import { Container, Row, Col } from "shards-react";
import "bootstrap/dist/css/bootstrap.min.css";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <Container>
        <Row>
          <Col sm={{ size: 6, order: 2, offset: 2 }}>2</Col>
          <Col sm={{ size: 2, order: 1, offset: 2 }}>1</Col>
        </Row>
      </Container>
    </div>
  );
}

to set the order property to change the order.

And we can change the offset to change the offset size.

Collapse

We can add a collapse component into our React app with Shards React.

For instance, we can write:

import React, { useState } from "react";
import { Button, Collapse } from "shards-react";
import "bootstrap/dist/css/bootstrap.min.css";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  const [collapse, setCollapse] = useState(false);

  const toggle = () => {
    setCollapse((c) => !c);
  };
  return (
    <div className="App">
      <Button onClick={toggle}>Toggle</Button>
      <Collapse open={collapse}>
        <div className="p-3 mt-3 border rounded">
          <h5>Lorem ipsum</h5>
          <span>Lorem ipsum</span>
        </div>
      </Collapse>
    </div>
  );
}

We have the collapse state which we pass into the open prop to control whether the Collapse component is displayed or not.

The Bootstrap styles are required for it to work properly.

Dropdown

We can add dropdowns with the Dropdown , DropdownToggle , DropdownMenu and DropdownItem components.

For instance, we can write:

import React, { useState } from "react";
import {
  Dropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem
} from "shards-react";
import "bootstrap/dist/css/bootstrap.min.css";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  const [open, setOpen] = useState(false);

  const toggle = () => {
    setOpen((c) => !c);
  };
  return (
    <div className="App">
      <Dropdown open={open} toggle={toggle}>
        <DropdownToggle>Dropdown</DropdownToggle>
        <DropdownMenu>
          <DropdownItem>Action</DropdownItem>
          <DropdownItem>Another action</DropdownItem>
          <DropdownItem>Something else here</DropdownItem>
        </DropdownMenu>
      </Dropdown>
    </div>
  );
}

We add the Dropdown component to add the dropdown container.

DropdownToggle has the dropdown rtoggle.

DropdownMenu has the dropdown menu.

DropdownItem has the dropdown items.

We set the open prop to control when it’s open.

The toggle prop has the toggle function to control the open state.

Fade

The Fade component lets us add a fade effect to our React app.

For instance, we write:

import React, { useState } from "react";
import { Fade, Button } from "shards-react";

import "bootstrap/dist/css/bootstrap.min.css";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  const [visible, setVisible] = useState(false);

  const toggle = () => {
    setVisible((c) => !c);
  };
  return (
    <div className="App">
      <Button onClick={toggle} className="mb-2">
        Toggle
      </Button>
      <Fade in={visible} className="p-1">
        lorem ipsum
      </Fade>
    </div>
  );
}

to add a Button to toggle the Fade component.

The in prop lets us set the visibility of the Fade component.

And the toggle function toggles the visible state to control Fade ‘s visibility.

Conclusion

We can add collapse, dropdowns, and fade effects into our React app with Shard React.

Categories
Shards React

Getting Started with React Development with the Shards React Library — Alert, Badge, and Breadcrumbs

Shards React is a useful UI library that lets us add many components easily into our React app.

In this article, we’ll look at how to use it to add components to our React app.

Installation

We can install the package by running:

yarn add shards-react

with Yarn or:

npm i shards-react

with NPM.

Bootstrap styles are required for some components.

We can add it by running:

npm i bootstrap

Alert

After we install the package, we can add an alert with the Alert component:

import React from "react";
import { Alert } from "shards-react";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <Alert theme="primary">Alert</Alert>
    </div>
  );
}

We import the CSS to import the styles.

We set the theme prop to set background color of the alert.

Other options include secondary , success , danger , info , light , and dark .

We can add a dismissible alert with the dismissible prop:

import React, { useState } from "react";
import { Alert } from "shards-react";
import "bootstrap/dist/css/bootstrap.min.css";
import "shards-ui/dist/css/shards.min.css";
export default function App() {
  const [visible, setVisible] = useState();
  const dismiss = () => {
    setVisible(false);
  };
  return (
    <div className="App">
      <Alert theme="primary" dismissible={dismiss} open={visible}>
        Alert
      </Alert>
    </div>
  );
}

We set the open prop to the visible state to let us control its visibility.

Badge

We can add a badge into our React app with the Badge component.

For instance, we can write:

import React from "react";
import { Badge } from "shards-react";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <Badge theme="secondary">Secondary</Badge>
    </div>
  );
}

The theme is set to secondary to display a gray background.

We can also set it to success , danger , info , light , and dark .

If we leave theme out, then it’s set to a blue background.

We can add the pill prop to make it pill-shaped:

import React from "react";
import { Badge } from "shards-react";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <Badge pill theme="secondary">
        Secondary
      </Badge>
    </div>
  );
}

And we can add the outline prop to make it outlined:

import React from "react";
import { Badge } from "shards-react";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <Badge outline theme="secondary">
        Secondary
      </Badge>
    </div>
  );
}

We can have both together.

And we can make it a link with the href prop:

import React from "react";
import { Badge } from "shards-react";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <Badge href="http://yahoo.com" theme="secondary">
        Secondary
      </Badge>
    </div>
  );
}

Breadcrumb

We can add a breadcrumb into our React app with the Breadcrumb and BreadcrumbItem components.

For instance, we can write:

import React from "react";
import { Breadcrumb, BreadcrumbItem } from "shards-react";
import "shards-ui/dist/css/shards.min.css";

export default function App() {
  return (
    <div className="App">
      <Breadcrumb>
        <BreadcrumbItem>
          <a href="#">Home</a>
        </BreadcrumbItem>
        <BreadcrumbItem active>Library</BreadcrumbItem>
      </Breadcrumb>
    </div>
  );
}

BreadcrumbItem has the items. href has the URL for the link.

Conclusion

We can add a few basic components into our React app with Shards React.

Categories
React

Make Form Handling Easy in React Apps with Formik — Hooks

Formik is a library that makes form handling in React apps easy.

In this article, we’ll look at how to handle form inputs with Formik

useField

We can use the useField hook to create our own text fields that work with Formik.

For instance, we can write:

import React from "react";
import { useField, Form, Formik } from "formik";

const MyTextField = ({ label, ...props }) => {
  const [field, meta] = useField(props);
  return (
    <>
      <label>
        {label}
        <input {...field} {...props} />
      </label>
      {meta.touched && meta.error ? (
        <div className="error">{meta.error}</div>
      ) : null}
    </>
  );
};

export const FormExample = () => (
  <div>
    <Formik
      initialValues={{
        email: ""
      }}
      onSubmit={(values, actions) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
        }, 1000);
      }}
    >
      {(props) => (
        <Form>
          <MyTextField name="email" type="email" label="Email" />
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);
export default function App() {
  return (
    <div className="App">
      <FormExample />
    </div>
  );
}

We create the MyTextField component with the useField hook.

And we pass in the props and the field objects into the input as props to let Formik bind to states and set input statuses like touched and error .

Then in FormExample , we create our form with the Formik and Form components as usual.

But we use the MyTextField component to add our input field into the form.

useFormik

We can use the useFormik hook to create Formik forms.

For instance, we can write:

import React from "react";
import { useFormik } from "formik";

export const FormExample = () => {
  const formik = useFormik({
    initialValues: {
      firstName: "",
      lastName: "",
      email: ""
    },
    onSubmit: (values) => {
      alert(JSON.stringify(values, null, 2));
    }
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="firstName">First Name</label>
      <input
        id="firstName"
        name="firstName"
        type="text"
        onChange={formik.handleChange}
        value={formik.values.firstName}
      />
      <label htmlFor="lastName">Last Name</label>
      <input
        id="lastName"
        name="lastName"
        type="text"
        onChange={formik.handleChange}
        value={formik.values.lastName}
      />
      <label htmlFor="email">Email Address</label>
      <input
        id="email"
        name="email"
        type="email"
        onChange={formik.handleChange}
        value={formik.values.email}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default function App() {
  return (
    <div className="App">
      <FormExample />
    </div>
  );
}

We add the useFormik to FormExample to let us create a form with Formik.

We pass the initialValues inside to set the initial values.

onSubmit has the submit handler for the form.

Then we can get the properties from the formik object.

This includes the onSubmit callback, which is set to formik.handleSubmit .

formik.handleChange is the change handler for the form fields.

form.values has the form values.

useFormikContext

We can use the useFormikContext hook to let us access the form from components inside the form.

For instance, we can write:

import React from "react";
import { Field, Form, Formik, useFormikContext } from "formik";

const AutoSubmitToken = () => {
  const { values, submitForm } = useFormikContext();
  React.useEffect(() => {
    if (values.token.length === 6) {
      submitForm();
    }
  }, [values, submitForm]);
  return null;
};

export const FormExample = () => {
  return (
    <Formik
      initialValues={{ token: "" }}
      validate={(values) => {
        const errors = {};
        if (values.token.length < 5) {
          errors.token = "Invalid code. Too short.";
        }
        return errors;
      }}
      onSubmit={(values, actions) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
        }, 1000);
      }}
    >
      <Form>
        <Field name="token" type="tel" />
        <AutoSubmitToken />
      </Form>
    </Formik>
  );
};

export default function App() {
  return (
    <div className="App">
      <FormExample />
    </div>
  );
}

We have the AutoSubmitToken component that has the values property with the form values.

submitForm has the form submit function.

useFormikContext returns an object with all those properties.

The FormExample has the usual props and components to create the form and the AutoSubmitToken component that submits the form automatically values.token.length is bigger than or equal to 6.

Conclusion

We can use the hooks that comes with Formik to create our forms.

Categories
React

Make Form Handling Easy in React Apps with Formik — Dependant Fields and Object Array Fields

Formik is a library that makes form handling in React apps easy.

In this article, we’ll look at how to handle form inputs with Formik

Dependent Fields

We can set one field’s value based on a value of another field.

For instance, we can write:

import React from "react";
import { Formik, Field, Form, useField, useFormikContext } from "formik";

const MyField = (props) => {
  const {
    values: { textA },
    touched,
    setFieldValue
  } = useFormikContext();
  const [field, meta] = useField(props);

  React.useEffect(() => {
    if (textA.trim() !== "" && touched.textA) {
      setFieldValue(props.name, `textA: ${textA}`);
    }
  }, [textA, touched.textA, setFieldValue, props.name]);

  return (
    <>
      <input {...props} {...field} />
      {!!meta.touched && !!meta.error && <div>{meta.error}</div>}
    </>
  );
};

const initialValues = { textA: "", textB: "" };

export const FormExample = () => (
  <div>
    <Formik
      initialValues={initialValues}
      onSubmit={async (values) => alert(JSON.stringify(values, null, 2))}
    >
      <Form>
        <label>
          textA
          <Field name="textA" />
        </label>
        <label>
          textB
          <MyField name="textB" />
        </label>
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  </div>
);
export default function App() {
  return (
    <div className="App">
      <FormExample />
    </div>
  );
}

We created the MyField component and use the useFormikContext component to get the status of the textA field.

We get its value from the values.textA property.

touched has the touched value.

setFieldValue lets us set the field value of another field.

We watch the value the textA field with the useEffect callback and the array with the textA field value, the touched.textA property which has the touched status of textA , setFieldValue , and props.name .

We watch all of them for changes.

Then in FormExample , we use MyField to create the textB field.

It watches the textA field for changes, so when we enter something into the textA field, we see the text of the textB set with the value of textA .

Object Array Fields

We can bind fields to an array of objects.

To do this, we write:

import React from "react";
import { Formik, Field, Form, FieldArray, ErrorMessage } from "formik";

const initialValues = {
  friends: [
    {
      name: "",
      email: ""
    }
  ]
};

export const FormExample = () => (
  <div>
    <Formik
      initialValues={initialValues}
      onSubmit={async (values) => {
        await new Promise((r) => setTimeout(r, 500));
        alert(JSON.stringify(values, null, 2));
      }}
    >
      {({ values }) => (
        <Form>
          <FieldArray name="friends">
            {({ remove, push }) => (
              <div>
                {values.friends.length > 0 &&
                  values.friends.map((friend, index) => (
                    <div className="row" key={index}>
                      <div className="col">
                        <label htmlFor={`friends.${index}.name`}>Name</label>
                        <Field name={`friends.${index}.name`} type="text" />
                        <ErrorMessage
                          name={`friends.${index}.name`}
                          component="div"
                          className="field-error"
                        />
                      </div>
                      <div className="col">
                        <label htmlFor={`friends.${index}.email`}>Email</label>
                        <Field name={`friends.${index}.email`} type="email" />
                        <ErrorMessage
                          name={`friends.${index}.name`}
                          component="div"
                          className="field-error"
                        />
                      </div>
                      <div className="col">
                        <button
                          type="button"
                          className="secondary"
                          onClick={() => remove(index)}
                        >
                          X
                        </button>
                      </div>
                    </div>
                  ))}
                <button
                  type="button"
                  className="secondary"
                  onClick={() => push({ name: "", email: "" })}
                >
                  Add
                </button>
              </div>
            )}
          </FieldArray>
          <button type="submit">Invite</button>
        </Form>
      )}
    </Formik>
  </div>
);

export default function App() {
  return (
    <div className="App">
      <FormExample />
    </div>
  );
}

We just set the name to the path of the property we want to bind to in the Field component.

Likewise, we do the same with the ErrorMessage field to get the form validation error messages for the field with the given property path.

To remove an entry, we can use the remove function that comes with Formik.

Conclusion

We can add dependant fields and bind fields to an array of objects with Formik.