Chips Input Field

Hello Fellow Developers, welcome back to another article of Material UI in this article we are going to create Input fields with chips.

We will be using react typescript for this and following dependencies are needed:-

First of all create react app using following command

npx create-react-app chipinput

Now install Material UI

npm install @mui/material @emotion/react @emotion/styled

Now add dowshift

npm i downshift

and we are good to go create a tabs input component and add following code

import React, { useEffect } from "react";
import PropTypes from "prop-types";
import Downshift from "downshift";
import { Chip, TextField } from "@mui/material";
import CloseIcon from '@mui/icons-material/Close';


export default function TagsInput({ ...props }) {
  const { selectedTags, placeholder, tags, ...other } = props;
  const [inputValue, setInputValue] = React.useState("");
  const [selectedItem, setSelectedItem] = React.useState([]);
  useEffect(() => {
    setSelectedItem(tags);
  }, [tags]);
  useEffect(() => {
    selectedTags?.(selectedItem);
  }, [selectedItem, selectedTags]);

  function handleKeyDown(event: any) {
    if (event.key === "Enter") {
      const newSelectedItem : any = [...selectedItem];
      const duplicatedValues = newSelectedItem.indexOf(
        event.target.value.trim()
      );

      if (duplicatedValues !== -1) {
        setInputValue("");
        return;
      }
      if (!event.target.value.replace(/\s/g, "").length) return;

      newSelectedItem.push(event.target.value.trim());
      setSelectedItem(newSelectedItem);
      setInputValue("");
    }
    if (
      selectedItem.length &&
      !inputValue.length &&
      event.key === "Backspace"
    ) {
      setSelectedItem(selectedItem.slice(0, selectedItem.length - 1));
    }
  }
  function handleChange(item) {
    let newSelectedItem : any = [...selectedItem];
    if (newSelectedItem.indexOf(item) === -1) {
      newSelectedItem = [...newSelectedItem, item];
    }
    setInputValue("");
    setSelectedItem(newSelectedItem);
  }

  const handleDelete = (item) => () => {
    const newSelectedItem : any = [...selectedItem];
    newSelectedItem.splice(newSelectedItem.indexOf(item), 1);
    setSelectedItem(newSelectedItem);
  };

  function handleInputChange(event) {
    setInputValue(event.target.value);
  }
  return (
    <React.Fragment>
      <Downshift
        id="downshift-multiple"
        inputValue={inputValue}
        onChange={handleChange}
        selectedItem={selectedItem}
      >
        {({ getInputProps }) => {
          const { onBlur, onChange, onFocus, ...inputProps } = getInputProps({
            onKeyDown: handleKeyDown,
            placeholder
          });
          return (
            <div className="overflow-y-auto flex flex-wrap">
              <TextField
                variant="standard"
                type={'text'}
                className= 'w-full overflow-y-auto flex flex-wrap text-white'
                InputProps={{
                  startAdornment: selectedItem.map((item) => (
                    <Chip
                      className="border rounded-none mr-1 bg-slate-300 text-sm mb-1 text-white"
                      //   style={{border: '1px', borderRadius: '1px'}}
                      key={item}
                      tabIndex={-1}
                      deleteIcon = {<CloseIcon />}
                      label={item}
                      onDelete={handleDelete(item)}
                    />
                  )),
                  onBlur,
                  onChange: (event : any) => {
                    handleInputChange(event);
                    onChange?.(event);
                  },
                  onFocus
                }}
                {...other}
                {...inputProps}
              />
            </div>
          );
        }}
      </Downshift>
    </React.Fragment>
  );
}
TagsInput.defaultProps = {
  tags: []
};
TagsInput.propTypes = {
  selectedTags: PropTypes.func.isRequired,
  tags: PropTypes.arrayOf(PropTypes.string)
};

I hope you understood the code for queries please contact me in comment section.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories