Categories
Ant Design Vue

Ant Design Vue — Dropdowns and Top Menus

Ant Design Vue or AntD Vue, is a useful UI framework made for Vue.js.

In this article, we’ll look at how to use it in our Vue apps.

Dropdown

We can add dropdowns with the a-dropdown component.

For example, we can write:

<template>
  <div id="app">
    <a-dropdown>
      <a class="ant-dropdown-link" @click="e => e.preventDefault()">Hover me
        <a-icon type="down"/>
      </a>
      <a-menu slot="overlay">
        <a-menu-item>
          <a href="javascript:;">1st menu item</a>
        </a-menu-item>
        <a-menu-item>
          <a href="javascript:;">2nd menu item</a>
        </a-menu-item>
      </a-menu>
    </a-dropdown>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

We add the a-dropdown with the a element being its trigger.

a-menu shows the menu.

Context Menu

Also, we can add a context menu by setting the trigger prop to the ['contextmenu'] array:

<template>
  <div id="app">
    <a-dropdown :trigger="['contextmenu']">
      <div
        :style="{
        textAlign: 'center',
        background: '#f7f7f7',
        height: '200px',
        lineHeight: '200px',
        color: '#777',
      }"
      >Right Click on here</div>
      <a-menu slot="overlay">
        <a-menu-item key="1">1st menu item</a-menu-item>
        <a-menu-item key="2">2nd menu item</a-menu-item>
        <a-menu-item key="3">3rd menu item</a-menu-item>
      </a-menu>
    </a-dropdown>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

Also, we can add a divider and disable menu items:

<template>
  <div id="app">
    <a-dropdown>
      <a class="ant-dropdown-link" @click="e => e.preventDefault()">Hover me
        <a-icon type="down"/>
      </a>
      <a-menu slot="overlay">
        <a-menu-item key="0">
          <a target="_blank" rel="noopener noreferrer" href="https://www.google.com/">1st menu item</a>
        </a-menu-item>
        <a-menu-item key="1">
          <a target="_blank" rel="noopener noreferrer" href="https://www.ebay.com/">2nd menu item</a>
        </a-menu-item>
        <a-menu-divider/>
        <a-menu-item key="3" disabled>3rd menu item(disabled)</a-menu-item>
      </a-menu>
    </a-dropdown>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

a-menu-divider adds the divider and the disabled prop disables the item.

The placement of the dropdown menu can be changed:

<template>
  <div id="app">
    <a-dropdown placement="bottomRight">
      <a-button>bottom right</a-button>
      <a-menu slot="overlay">
        <a-menu-item key="0">
          <a target="_blank" rel="noopener noreferrer" href="https://www.google.com/">1st menu item</a>
        </a-menu-item>
        <a-menu-item key="1">
          <a target="_blank" rel="noopener noreferrer" href="https://www.ebay.com/">2nd menu item</a>
        </a-menu-item>
      </a-menu>
    </a-dropdown>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

We set the placement prop to change the placement.

Menu

We can add a menu with the a-menu component as the container and a-menu-item for the menu items:

<template>
  <div id="app">
    <a-menu v-model="current" mode="horizontal">
      <a-menu-item key="mail">
        <a-icon type="mail"/>Navigation One
      </a-menu-item>
      <a-menu-item key="app" disabled>
        <a-icon type="appstore"/>Navigation Two
      </a-menu-item>
      <a-sub-menu>
        <span slot="title" class="submenu-title-wrapper">
          <a-icon type="setting"/>Navigation Three - Submenu
        </span>
        <a-menu-item-group title="Item 1">
          <a-menu-item key="setting:1">Option 1</a-menu-item>
          <a-menu-item key="setting:2">Option 2</a-menu-item>
        </a-menu-item-group>
        <a-menu-item-group title="Item 2">
          <a-menu-item key="setting:3">Option 3</a-menu-item>
          <a-menu-item key="setting:4">Option 4</a-menu-item>
        </a-menu-item-group>
      </a-sub-menu>
      <a-menu-item key="google">
        <a
          href="https://google.com"
          target="_blank"
          rel="noopener noreferrer"
        >Navigation Four - Link</a>
      </a-menu-item>
    </a-menu>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

Conclusion

We can add a dropdown and top menu with Ant Design Vue.

Categories
Top React Libraries

Top React Libraries — Date Picker, Input Mask, and Tables

To make developing React apps easier, we can add some libraries to make our lives easier.

In this article, we’ll look at some popular libraries for React apps.

react-datetime

The react-datetime package lets us add a date or time picker to our app.

To install it, we run:

npm i react-datetime moment

Then we can use it by writing:

import React from "react";
const Datetime = require("react-datetime");

export default function App() {
  return (
    <div>
      <Datetime />
    </div>
  );
}

This will show a date picker that we can select a date from.

We can also customize the appearance of the date picker by writing:

import React from "react";
const Datetime = require("react-datetime");

const renderDay = (props, currentDate, selectedDate) => {
  const date = currentDate.date();
  return <td {...props}>{date < 10 ? "0" + date : date}</td>;
};

const renderMonth = (props, month, year, selectedDate) => {
  return <td {...props}>{month}</td>;
};

const renderYear = (props, year, selectedDate) => {
  return <td {...props}>{year % 100}</td>;
};

export default function App() {
  return (
    <div>
      <Datetime
        renderDay={renderDay}
        renderMonth={renderMonth}
        renderYear={renderYear}
      />
    </div>
  );
}

We added 3 functions to render the day, month, and year differently than the default way.

We can change the date format, time format, locale, value, and more.

Also, we can make it a controlled component by writing:

import React from "react";
const Datetime = require("react-datetime");

export default function App() {
  const [value, setValue] = React.useState(new Date());

  return (
    <div>
      <Datetime value={value} onChange={val => setValue(val.toDate())} />
    </div>
  );
}

We pass in the value to get the value and onChange to set it.

val is a moment object, so we’ve to convert to a Date instance with toDate .

rc-table

rc-table is a package that lets us add tables easily in our React app.

To install it, we run:

npm i rc-table

Then we write:

import React from "react";
import Table from "rc-table";

const columns = [
  {
    title: "Name",
    dataIndex: "name",
    key: "name",
    width: 100
  },
  {
    title: "Age",
    dataIndex: "age",
    key: "age",
    width: 100
  },
  {
    title: "Address",
    dataIndex: "address",
    key: "address",
    width: 200
  },
  {
    title: "Operations",
    dataIndex: "",
    key: "operations",
    render: () => <a href="#">Delete</a>
  }
];

const data = [
  { name: "james", age: 22, address: "some where", key: "1" },
  { name: "mary", age: 33, address: "some where", key: "2" }
];

export default function App() {
  return (
    <div>
      <Table columns={columns} data={data} />
    </div>
  );
}

to use it.

We have the columns defined in the columns array.

title has the headings.

dataIndex has the property key of the of the entry to display for that column.

key is the unique key of the column.

width has the column width in pixels.

render has the component to render.

data has the data, which is an array of objects.

In App , we use the provided Table component with the columns prop with the columns. data has the data to display.

react-input-mask

react-input-mask provides us with an easy to use input mask.

To install it, we run:

npm i react-input-mask

Then we can use it by writing:

import React from "react";
import InputMask from "react-input-mask";

export default function App() {
  return (
    <div>
      <InputMask mask="+49 999 999 9999" maskChar=" " />
    </div>
  );
}

We use the InputMask component to add the input.

mask has the pattern to restrict the input to.

maskChar is the character to cover the unfilled parts of the mask.

We can also change the characters for formatting in the mask.

Also, we can use it with Material UI.

We can also turn it to a controlled component with the value and onChange props:

import React from "react";
import InputMask from "react-input-mask";

export default function App() {
  const [value, setValue] = React.useState("");

  return (
    <div>
      <InputMask
        value={value}
        onChange={e => setValue(e.target.value)}
        mask="+49 999 999 9999"
        maskChar=" "
      />
    </div>
  );
}

We use the onChange callback to set the inputted value as the value of the value state.

And we pass the value state as the value of the value prop.

Conclusion

react-datetime is a date and time picker we can use in our React app.

rc-table is a table component.

react-input-mask is an input mask component.

Categories
Top React Libraries

Top React Libraries — Swipes and Collapse

To make developing React apps easier, we can add some libraries to make our lives easier.

In this article, we’ll look at some popular libraries for React apps.

react-swipeable-views

react-swipeable-views is an easy to use package to let us add swipes gesture handling to our React app.

To use it, we install it by running:

npm i react-swipeable-views

Then we can use it by writing:

import React from "react";
import SwipeableViews from "react-swipeable-views";

const styles = {
  slide: {
    padding: 15,
    minHeight: 100,
    color: "black"
  },
  slide1: {
    background: "lightgreen"
  },
  slide2: {
    background: "lightblue"
  },
  slide3: {
    background: "orange"
  }
};

export default function App() {
  return (
    <div>
      <SwipeableViews>
        <div style={Object.assign({}, styles.slide, styles.slide1)}>
          slide 1
        </div>
        <div style={Object.assign({}, styles.slide, styles.slide2)}>
          slide 2
        </div>
        <div style={Object.assign({}, styles.slide, styles.slide3)}>
          slide 3
        </div>
      </SwipeableViews>
    </div>
  );
}

We just import the SwipeableViews component.

Then we add divs to in between the tags to add slides.

It also has experimental support for React Native.

We can also add the resistance bound effect with the resistance prop:

import React from "react";
import SwipeableViews from "react-swipeable-views";

const styles = {
  slide: {
    padding: 15,
    minHeight: 100,
    color: "black"
  },
  slide1: {
    background: "lightgreen"
  },
  slide2: {
    background: "lightblue"
  },
  slide3: {
    background: "orange"
  }
};

export default function App() {
  return (
    <div>
      <SwipeableViews resistance>
        <div style={Object.assign({}, styles.slide, styles.slide1)}>
          slide 1
        </div>
        <div style={Object.assign({}, styles.slide, styles.slide2)}>
          slide 2
        </div>
        <div style={Object.assign({}, styles.slide, styles.slide3)}>
          slide 3
        </div>
      </SwipeableViews>
    </div>
  );
}

Also, we can put our slides in the VirtualizeSwipeableViews component if we have many slides to load.

This way, they’re only loaded when they’re shown:

import React from "react";
import SwipeableViews from "react-swipeable-views";
import { virtualize, bindKeyboard } from "react-swipeable-views-utils";
import { mod } from "react-swipeable-views-core";

const VirtualizeSwipeableViews = bindKeyboard(virtualize(SwipeableViews));

const styles = {
  slide: {
    padding: 15,
    minHeight: 100,
    color: "black"
  },
  slide1: {
    backgroundColor: "lightgreen"
  },
  slide2: {
    backgroundColor: "orange"
  },
  slide3: {
    backgroundColor: "pink"
  }
};

function slideRenderer(params) {
  const { index, key } = params;
  let style;

  switch (mod(index, 3)) {
    case 0:
      style = styles.slide1;
      break;

    case 1:
      style = styles.slide2;
      break;

    case 2:
      style = styles.slide3;
      break;

  default:
      break;
  }

  return (
    <div style={Object.assign({}, styles.slide, style)} key={key}>
      {`slide ${index + 1}`}
    </div>
  );
}

export default function App() {
  const [index, setIndex] = React.useState(0);

  const handleChangeIndex = i => {
    setIndex(i);
  };

  const handleClick = () => {
    setIndex(19);
  };
  return (
    <div>
      <VirtualizeSwipeableViews
        index={index}
        onChangeIndex={handleChangeIndex}
        slideRenderer={slideRenderer}
      />
      <br />
      <button onClick={handleClick}>go to slide 20</button>
    </div>
  );
}

We created the slideRendered component to render the slide.

And then we pass that into the slideRenderer prop.

The index prop has the index of the slide.

We can change that programmatically to jump to the slide we want.

rc-collapse

rc-collapse is a package that we can create collapse components with.

To install it, we run:

npm i rc-collapse

Then we can use it by writing:

import React from "react";
import "rc-collapse/assets/index.css";
import Collapse, { Panel } from "rc-collapse";

const getItems = () => {
  const items = Array(10)
    .fill()
    .map((_, i) => (
      <Panel
        header={`This is panel header`}
        key={i}
        extra={<span>Extra</span>}
        defaultActiveKey="1"
      >
        <p>Panel with extra</p>
      </Panel>
    ));

  return items;
};

export default function App() {
  const [activeKey, setActiveKey] = React.useState(0);

  const onChange = activeKey => {
    setActiveKey(activeKey);
  };

  return (
    <div style={{ margin: 20, width: 400 }}>
      <button onClick={() => setActiveKey(8)}>active header 7</button>
      <br />
      <Collapse accordion activeKey={activeKey} onChange={onChange}>
        {getItems()}
      </Collapse>
    </div>
  );
}

We have the getItems function to return an array of Collapse components, which has a heading, text on the right, and text in the panel.

The extra prop has the text on the right side of the header.

In App , we have the Collapse component with the activeKey prop.

This prop sets the active collapse item. The full panel will be displayed if it’s active.

We set it when we click on the button.

The onChange function changes the activeKey so that the correct item will be expanded.

Conclusion

react-swipeable-views lets us handle swiping of elements.

rc-collapse lets us add collapse component to our React app.

Categories
Top React Libraries

Top React Libraries — Text Boxes and Drag and Drop

To make developing React apps easier, we can add some libraries to make our lives easier.

In this article, we’ll look at some popular libraries for React apps.

react-textarea-autosize

We can use the react-textarea-autosize to add a text area that resizes automatically.

For example, we can run:

npm i react-textarea-autosize

to install it.

Then we can use it by writing:

import React from "react";
import TextareaAutosize from "react-textarea-autosize";

export default function App() {
  const [value, setValue] = React.useState("");
  return (
    <div>
      <TextareaAutosize
        rows={20}
        value={value}
        onChange={e => setValue(e.target.value)}
      />
    </div>
  );
}

We use the TextareaAutosize component that comes with the package.

It can be used as a controlled component as we did in the example.

We added the value prop to add the value and onChange to let us update the value state with it.

react-dnd

react-dnd is a library that lets us add drag and drop features to our React app.

To use it, we can install it by running:

yarn add react-dnd react-dnd-html5-backend

Then we can use it by writing the following code:

import React from "react";
import { DndProvider, useDrag, useDrop } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";

const Box = ({ name }) => {
  const [{ isDragging }, drag] = useDrag({
    item: { name, type: "box" },
    end: (item, monitor) => {
      const dropResult = monitor.getDropResult();
      if (item && dropResult) {
        alert(`You dropped ${item.name} into ${dropResult.name}!`);
      }
    },
    collect: monitor => ({
      isDragging: monitor.isDragging()
    })
  });
  const opacity = isDragging ? 0.4 : 1;
  return (
    <div ref={drag} style={{ opacity }}>
      {name}
    </div>
  );
};

const Dustbin = () => {
  const [{ canDrop, isOver }, drop] = useDrop({
    accept: "box",
    drop: () => ({ name: "Dustbin" }),
    collect: monitor => ({
      isOver: monitor.isOver(),
      canDrop: monitor.canDrop()
    })
  });
  const isActive = canDrop && isOver;
  let backgroundColor = "#222";
  if (isActive) {
    backgroundColor = "yellow";
  } else if (canDrop) {
    backgroundColor = "green";
  }
  return (
    <div ref={drop} style={{ backgroundColor }}>
      {isActive ? "Release to drop" : "Drag a box here"}
    </div>
  );
};

export default function App() {
  return (
    <div>
      <DndProvider backend={HTML5Backend}>
        <Dustbin />
        <Box name="foo" />
        <Box name="bar" />
      </DndProvider>
    </div>
  );
}

We have the DndProvider that wraps around the components that can be dragged or we can drop stuff into.

The Dustbin component is where we can drop stuff into.

We watch for items that we’re dropping with the useDrop hook.

accept is the type of item that it accepts.

drop is the function that runs when something is dropped into it.

collect is a function that returns whether the item can be dropped or not.

We have the isActive variable which checks if the item can be dropped, which is done by checking the type .

isOver checks if the dropping is done.

Then we render the background and text according to that.

We created a draggable item by creating the Box component.

We used the useDrag hook to create a draggabkle component.

The name prop has the content of the draggable element.

We get the result of the dragging with the end callback in the useDrag hook.

collect has a function that runs to check if it’s being dragged.

Now we can drag the Box to the Dustbin and we’ll get an alert every time we do so.

React-Input-Autosize

We get an autoresize input box with the React-Input-Autoresize package.

To install it, we can run:

npm i react-input-autosize

Then we use it by writing:

import React from "react";
import AutosizeInput from "react-input-autosize";

export default function App() {
  const [value, setValue] = React.useState("example");
  return (
    <div>
      <AutosizeInput
        name="form-field"
        value={value}
        onChange={e => setValue(e.target.value)}
      />
    </div>
  );
}

We created a controlled text box that resizes according to the inputted value by setting the value prop with a state and the onChange with a function to change the state.

Conclusion

React-dnd is a useful drag and drop library that lets us do many things.

React-textarea-autoresize and React-input-autoresize are 2 popular resizable text boxes we can use to enter text.

Categories
Top React Libraries

Top React Libraries — Tooltip, Clipboard, Dates, and Portal

To make developing React apps easier, we can add some libraries to make our lives easier.

In this article, we’ll look at some popular libraries for React apps.

react-tooltip

react-tooltip is an easy to use tooltip component.

To install it, we can run:

npm i react-tooltip

Then we can use it by writing:

import React from "react";
import ReactTooltip from "react-tooltip";

export default function App() {
  return (
    <>
      <p data-tip="hello world">Tooltip</p>
      <ReactTooltip />
    </>
  );
}

We add an element with the data-tip attribute with the value being the text that we want to display in the tooltip.

Then we add the ReactTooltip component.

This will display the text in the tooltip when we hover it.

We can change many other things like offsets, delays, borders, arrow colors, and much more.

react-copy-to-clipboard

react-copy-to-clipboard is a package that lets us copy things to the clipboard easier when the user does something our React app.

To install it, we can write:

npm i react-copy-to-clipboard

Then we can use it by writing:

import React from "react";
import { CopyToClipboard } from "react-copy-to-clipboard";

export default function App() {
  const [value, setValue] = React.useState("");
  const [copied, setCopied] = React.useState(false);
  return (
    <>
      <div>
        <input
          value={value}
          onChange={({ target: { value } }) => setValue(value)}
        />

        <CopyToClipboard text={value} onCopy={() => setCopied(true)}>
          <span>Copy to clipboard with span</span>
        </CopyToClipboard>

        <CopyToClipboard text={value} onCopy={() => setCopied(true)}>
          <button>Copy to clipboard with button</button>
        </CopyToClipboard>

{copied ? <span style={{ color: "red" }}>Copied.</span> : null}
      </div>
    </>
  );
}

We have the CopyToClipboard component which surrounds the component that we to let user use to copy content to the clipboard.

The text prop has the values that we want to let the user copy to the clipboard.

React-portal

React-portal is a package that lets us use the React portal feature easily.

It lets us render our component as a child of any element we want.

We can install it by running:

npm i react-portal

Then we can use it by writing:

import React from "react";
import { Portal } from "react-portal";

export default function App() {
  return (
    <>
      <Portal>This text is portaled at the end of document.body!</Portal>

      <Portal node={document && document.getElementById("foo")}>
        This text is portaled into foo
      </Portal>
    </>
  );
}

We use the Portal component to render our content in the location we want in the DOM.

If there’s node prop, then it’s rendered in the body.

Otherwise, it’s rendered in the element that we specified.

react-dates

react-dates is a date picker library for our React app.

To install it, we can run:

npm i react-dates

Then we can use it by writing:

import React from "react";
import { DateRangePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

export default function App() {
  const [startDate, setStartDate] = React.useState(null);
  const [endDate, setEndDate] = React.useState(null);
  const [focusedInput, setFocusedInput] = React.useState(null);
  return (
    <>
      <DateRangePicker
        startDateId="startDate"
        endDateId="endDate"
        startDate={startDate}
        endDate={endDate}
        onDatesChange={({ startDate, endDate }) => {
          setStartDate(startDate);
          setEndDate(endDate);
        }}
        focusedInput={focusedInput}
        onFocusChange={focusedInput => {
          setFocusedInput(focusedInput);
        }}
      />
    </>
  );
}

We have the startDateId to set the name of the start date field.

We do the same with the end date with the endDateId

startDate has the value of the start date.

endDate has the end date value.

onDatesChange has a function that updates the state of the start date.

focusedInput has the input that’s focused.

onFocusChange has the function to set which date input is focused.

We also have to import the initialize module and the CSS to make the pickers display properly.

Conclusion

react-tooltip lets us add a tooltip easily.

react-copy-to-clipboard lets us add a copy to clipboard feature in our React app.

React-portal has makes using the portal feature easy.

react-dates lets us add a start and end date picker.