JSFiddle - React, Tailwind, and code Playground

by andrew rowe

HTML

<div id="view">

  <h1 data-bind="text: questionText"></h1>

	<!-- ko foreach: answers -->
		<div class="mb-2 d-flex justify-content-between align-items-center">
			<div class="mr-2 text-nowrap">
				<button data-bind="click: ()=>$parent.moveUp, enable: $index() > 0">Up</button>
				<button data-bind="click: ()=>$parent.moveDown, enable: $index() < $parent.answers().length-1">Down</button>
			</div>
			<div class="pr-2 flex-grow-1 input-group w-auto">
				<div class="input-group-prepend">
					<span class="input-group-text mr-2" style="width: 3rem;" data-bind="text: '#'+($index()+1)"></span>
				</div>
				<input type="text" data-bind="value: title" class="form-control" placeholder="Enter answer text here ...">
			</div>
			<div class="d-flex w-auto align-items-center">
				<label class="border btn btn-light rounded m-0 mr-2">
					<input data-bind="attr: {name: $index}, checked: correct" value="1" type="radio" class="mr-2"> Correct
				</label>
				<label class="border btn btn-light rounded m-0 mr-2">
					<input data-bind="attr: {name: $index}, checked: correct" value="0" type="radio" class="mr-2"> Incorrect
				</label>
			</div>
		</div>
	<!-- /ko -->
</div>

CSS

.d-flex, .input-group { display: flex; }
.mb-2 { margin-bottom: 0.5rem; }
.mr-2 { margin-right: 0.5rem; }
.justify-content-between { justify-content: between; }
.align-items-center { align-items: center; }

JavaScript

class Answer {
  constructor(question, title, correct) {
    this.question = question;
    this.title = title;
    this.correct = ko.observable(correct);
  }

}

class VM {
  constructor(questionText, answers) {
    this.questionText = questionText;
    this.answers = ko.observableArray(
      answers.map(answer =>
        new Answer(this, answer.title, answer.correct)
      )
    );
  }
  
  moveUp(answer){
  this.swap(answer,1)
  }
  
  moveDown(answer){
  this.swap(answer, -1)
  }

  swap(answer, direction) {
    const i = this.answers.indexOf(answer);
    console.log(i, answer)
    if (i > 0) {
      let array = this.answers();
      array.splice(i - direction, 2, array[i], array[i - direction])
      this.answers(array);
    }
  }
}


var questionText = 'What is 1 + 1';
var answers = [{
    title: 'One',
    correct: '0'
  },
  {
    title: 'Two',
    correct: '1'
  },
  {
    title: 'Three',
    correct: '0'
  },
  {
    title: 'Four',
    correct: '0'
  },
  {
    title: 'Three',
    correct: '0'
  },
];

ko.applyBindings(new VM(questionText, answers), document.getElementById('view'));