I am generating a random number of inputs which will each collect a word. I want to then take all of those individual words and create an array of words (eventually to display that array). I am new to react and am using onChange for my inputs but all I get is a blob of all the words together. I don't know how to take the index of each of the inputs and put it into an array on submit. I don't know if I should use onSubmit or onChange. I guess I am not sure how to collect the information from each input on submit. do I use key={index} along with the event.target.value, do I just make an array of event.target.value?
Here is the Code Sandbox:
https://codesandbox.io/s/jovial-euler-swfs7?file=/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { Image } from './Image.js'
import { Button } from './Button.js'
import { images } from './assets/images.js'
import { Countdown } from './Countdown.js'
import { DisplayCount } from './DisplayCount.js'
import { Inputs } from './Inputs.js'
class Game extends React.Component{
constructor(props){
super(props)
this.timer = null
this.state = {
currentImg: 0,
timer: null,
ranNum: null,
thought: null
}
this.handleClick = this.handleClick.bind(this)
}
countdownClock = async (newRanNum) => {
const startingNum = newRanNum * 20;
for(let i = startingNum; i >= 0; i--) {
await new Promise(resolve => {
this.timer = setTimeout(() => {
this.setState({
timer: i
})
resolve()
}, 1000)
});
}
}
handleChange(event) {
this.setState({
thought: event.target.value
})
}
handleSubmit(event) {
}
generateInputs = (newRanNum) => {
const inputs = []
for(let i = 1; i <= newRanNum; i++){
inputs.push(
<Inputs type='text' onChange={this.handleChange} className='textInputs' />
)
}
return inputs;
}
handleClick(){
clearTimeout(this.timer)
let newRanNum = Math.floor(Math.random() * 20);
this.countdownClock(newRanNum)
this.generateInputs(newRanNum)
let current = this.state.currentImg;
let next = ++current % images.length;
this.setState({
currentImg: next,
ranNum: newRanNum
})
}
render(){
let src = this.state.currentImg;
return(
<div>
<Countdown name={'Countdown: '} countdown={this.state.timer} />
<DisplayCount name='Word Count: ' count={this.state.ranNum} />
<Image src={images[src]} />
<Button onClick={this.handleClick} />
<form onSubmit={this.handleSubmit}>
<ul>
{this.generateInputs(this.state.ranNum)}
</ul>
<input type='submit' value='Submit' />
</form>
</div>
)
}
}
ReactDOM.render(
<Game />,
document.getElementById('root')
);