JSFiddle - React, Tailwind, and code Playground

by Jehuty

HTML

<div class="name-form js-name-form">
  <div class="name-form-control">
    <input type="text" class="js-name-form-firstname name-form__input">
    <input type="text" class="js-name-form-surname name-form__input">
  </div>
  <div class="name-form-control">
    <button class="js-name-form__add name-form__btn">Add</button>
  </div>
</div>

SCSS

.name-form {
  &-control {
    font-size: 0;
  }

  &-control + &-control {
    margin-top: 10px;
    white-space: prewrap;
  }

  &__input {
    display: inline-block;
    font-size: 13px;
  }

  &__input + &__input {
    margin-left: 5px;
  }

  &__btn + &__btn {
    margin-left: 5px;
  }

  &__removebtn {
    padding: 1px 3px;
    display: inline-block;
    line-height: 16px;
    font-size: 13px;
    margin-left: 5px;
  }
}

JavaScript

const form = document.querySelector('.js-name-form');
const addBtn = form.querySelector('.js-name-form__add');

function addFormRow() {
	const last = form.querySelector('.name-form-control:last-of-type');
  const secondLast = last.previousSibling;

  const rowContainer = document.createElement('div');
  rowContainer.classList.add('name-form-control');
  const inputFirstname = document.createElement('input');
  inputFirstname.classList.add('js-name-form-firstname');
  inputFirstname.classList.add('name-form__input')
  inputFirstname.type = 'text';
  const inputLastname = document.createElement('input');
  inputLastname.classList.add('js-name-form-surname');
  inputLastname.classList.add('name-form__input')
  inputLastname.type = 'text';
  const removeBtn = document.createElement('button');
  removeBtn.classList.add('js-name-form-removebtn');
  removeBtn.classList.add('name-form__removebtn')
  removeBtn.innerHTML = 'âś•';
  rowContainer.appendChild(inputFirstname);
  rowContainer.appendChild(inputLastname);
  rowContainer.appendChild(removeBtn);
 
  last.parentNode.insertBefore(rowContainer, last);
	inputFirstname.focus();
}

addBtn.addEventListener('click', addFormRow)

document.addEventListener('click', (e) => {
	if (e.target && e.target.classList.contains('js-name-form-removebtn')) {
  	const btn = e.target;
    btn.parentNode.parentNode.removeChild(btn.parentNode);
  }
})

document.addEventListener('keypress', (e) => {
	if (e.target && (e.target.classList.contains('js-name-form-firstname') ||
  								 e.target.classList.contains('js-name-form-surname'))) {
    const key = e.which || e.keyCode;
  	if (key === 13) {
    	addFormRow();
    }                 
  }
})