My logic might seem a bit off cause I'm pretty new to react and typescript. I created an input component that generates input element according to the length of a word which comes in as props, when a user types the word, I want to be able to get the value of each input and store them into one variable, I tried concatenating the input values of the individual input element but the output still comes out individually.Thanks
import React, {useState} from 'react'
interface Props{
word: string,
setScoreHandler: (event: any) => void
}
const Input: React.FC<Props> = ({word, setScoreHandler}) => {
const [words, setWords] = useState('')
const textArray = word.split('')
const appendWord = (e: { target: { value: string } }) => {
let inputValue = ''
let inputValue1 = inputValue.concat(e.target.value)
setWords(inputValue1)
console.log(inputValue1)
}
const style: React.CSSProperties = {
MozBoxShadow : "inset 0 0 10px #000000",
WebkitBoxShadow : "inset 0 0 10px #000000",
boxShadow : "inset 0 0 10px #000000",
}
return (
<>
{textArray.map(text => (
<input style={style} key={text} type="text" maxLength="1" onChange={appendWord} className='w-11 h-20 bg-walnut text-center text-3xl rounded-lg ml-3 shadow-inner-lg'/>
))}
</>
)
}
export default Input
CodePudding user response:
First of all, console.log(words)
is not going to give you the updated value of words, since the setState
process is sorta async.
To track each input, you need to maybe use their indexes. I suggest modifying the jsx to
{textArray.map((text, index )=> (
<input style={style} key={text} type="text" maxLength="1" onChange={e => appendWord(e, index)} className='w-11 h-20 bg-walnut text-center text-3xl rounded-lg ml-3 shadow-inner-lg'/>
))}
Then modify appendWord to look like:
const appendWord = (e: { target: { value: string } }, index: number) => {
const newWords = words.split('');
newWords[index] = e.target.value;
setWords(newWords.join(''));
}
To see the newly updated words, you need a useEffect
.
useEffect(() => {
// would only be logged when words is changed.
console.log(words);
}, [words])
Hope this helps.