How to insert multiple phones in a tag next to, from a enter or tab, or even a button? React

Asked

Viewed 23 times

0

I want the phone input, when adding, and the user click enter or tab, (or even an add button or +), it inserts the phone in the side tags, (can be below or even within the input itself - just like this page when you insert the question subject tag).

inserir a descrição da imagem aqui

But I couldn’t do the setChipData, read the setTelefone dynamically.

I have that code:

const handleDelete = (chipToDelete) => () => {
  setChipData((chips) => chips.filter((chip) => chip.key !== chipToDelete.key));
};

const [chipData, setChipData] = React.useState([
  { key: 0, label: '(31) 9999-9999' },
  { key: 1, label: '(32) 9888-8888' },
]);

return (
    <div className="register-container">
      <div className="content">
          <div className="input-group">
            <InputMask
              placeholder="Telefone"
              value={telefone}
              mask={["(99) 9999-9999", "(99) 9 9999-9999"]}
              onChange={setTelefone}
            />
            <Paper component="ul" className={classes.root}>
              {chipData.map((data) => {
                let icon;

                return (
                  <li key={data.key}>
                    <Chip
                      icon={icon}
                      label={data.label}
                      onDelete={handleDelete(data)}
                      className={classes.chip}
                    />
                  </li>
                );
              })}
            </Paper>
          </div>
      </div>
    </div>
  );
}

Here’s the demo of Material ui, I just couldn’t get it to take input. https://codesandbox.io/s/93bfb?file=/demo.js

1 answer

1


You need two states: the textual input and an array of phones. As these states are related, it is better to use the hook useReducer that use two useState. We have 3 possible actions: type something, press enter to submit a new phone and delete a phone.

function Chips({ items, deleteItem }) {
  const classes = useStyles();

  const handleDelete = (id) => {
    deleteItem(id);
  };

  return (
    <div className={classes.chipsRoot}>
      {items.map((item) => (
        <Chip key={item} label={item} onDelete={() => handleDelete(item)} />
      ))}
    </div>
  );
}

const reducer = (state, action) => {
  console.log(("action", action));

  switch (action.type) {
    case "input":
      return { ...state, input: action.input };
    case "enter":
      const { telefones, input } = state;
      const itemExiste = telefones.find((item) => item === input) != null;

      return {
        ...state,
        input: "",
        telefones: itemExiste ? telefones : [...telefones, input]
      };
    case "delete":
      return {
        ...state,
        telefones: state.telefones.filter((item) => item !== action.id)
      };
    default:
      throw new Error("Ação não existe");
  }
};

export default function BasicTextFields() {
  const classes = useStyles();

  const [{ input, telefones }, dispatch] = useReducer(reducer, {
    input: "",
    telefones: []
  });

  const onChange = (event) => {
    dispatch({ type: "input", input: event.target.value });
  };

  const onSubmit = (event) => {
    event.preventDefault();
    dispatch({ type: "enter" });
  };

  const deleteItem = (id) => {
    dispatch({ type: "delete", id });
  };

  return (
    <form
      onSubmit={onSubmit}
      className={classes.root}
      noValidate
      autoComplete="off"
    >
      <div>
        <TextField
          value={input}
          onChange={onChange}
          id="outlined-basic"
          label="Outlined"
          variant="outlined"
        />

        <Chips items={telefones} deleteItem={deleteItem} />
      </div>
    </form>
  );
}

Edit cocky-blackwell-1xhhp

Browser other questions tagged

You are not signed in. Login or sign up in order to post.