diff --git a/src/components/AnswerKeyForm/index.js b/src/components/AnswerKeyForm/index.js index 006742e..00ee2a4 100644 --- a/src/components/AnswerKeyForm/index.js +++ b/src/components/AnswerKeyForm/index.js @@ -8,9 +8,11 @@ class AnswerKeyForm extends React.Component { this.state = { courseName: '', - answers: Array(props.numberOfTests * props.numberOfQuestionsPerTest).fill( - null - ), + numTests: 10, + numQuestionsPerTest: 10, + answers: Array( + props.defaultNumTests * props.defaultNumQuestionsPerTest + ).fill(null), }; this.handleInputChange = this.handleInputChange.bind(this); @@ -18,6 +20,17 @@ class AnswerKeyForm extends React.Component { console.log(this.state.answers); } + componentDidUpdate(prevProps, prevState) { + // resize the answers array (and clear it) if + // the size parameters were changed + if ( + this.state.numTests !== prevState.numTests || + this.state.numQuestionsPerTest !== prevState.numQuestionsPerTest + ) { + this.updateAnswersSize(); + } + } + handleAnswerChange(target, answerIndex) { const answers = this.state.answers.slice(); answers[answerIndex] = target.value; @@ -29,27 +42,47 @@ class AnswerKeyForm extends React.Component { console.log(answers); } + updateAnswersSize() { + const newSize = this.state.numTests * this.state.numQuestionsPerTest; + const resizedAnswers = Array(newSize).fill(null); + const prevAnswers = this.state.answers.slice(); + + for ( + let i = 0; + i < Math.min(resizedAnswers.length, prevAnswers.length); + i++ + ) { + resizedAnswers[i] = prevAnswers[i]; + } + + this.setState({ + answers: resizedAnswers, + }); + } + handleInputChange(event) { const target = event.target; - const value = target.value; + const value = + target.type === 'number' ? Number(target.value) : target.value; const name = target.name; this.setState({ [name]: value, }); - - console.log(this.state); } render() { - const testRows = [...Array(this.props.numberOfTests).keys()].map( + const testRows = [...Array(this.state.numTests).keys()].map( (test, index) => ( - this.handleAnswerChange(target, (test + 1) * question) + this.handleAnswerChange( + target, + test * this.state.numQuestionsPerTest + question + ) } /> ) @@ -67,17 +100,38 @@ class AnswerKeyForm extends React.Component { onChange={this.handleInputChange} /> +
+
+ + +
+
+ + +
+
+ - {testRows}
+ Test answers
- + ); diff --git a/src/components/App.js b/src/components/App.js index 42dc730..141143e 100644 --- a/src/components/App.js +++ b/src/components/App.js @@ -8,7 +8,7 @@ class App extends Component {
- +
);