I have not found a post which answers issue with dynamic fields which are added based on lets say array length.
const [otherSources, setOtherSources] = useState<Source[]>([])
const SourceView = (source: Source & { index: number }) => {
return <div>
<div className="field">
<label className="label">Name</label>
<div className="control">
<input className="input" onChange={(event) => {
const copyOtherSources = otherSources
const sourceElement = copyOtherSources[source.index]
sourceElement.name = event.target.value
setOtherSources([...copyOtherSources])
}} value={source.name} />
</div>
</div>
<div className="field">
<label className="label">Url</label>
<div className="control">
<textarea className="textarea" onChange={(event) => {
const copyOtherSources = otherSources
const sourceElement = copyOtherSources[source.index]
sourceElement.url = event.target.value
setOtherSources([...copyOtherSources])
}} rows={2} value={source.url} />
</div>
</div>
</div>
}
return (
<div className="field">
<label className="label">Other Sources (comma separated)</label>
{
(otherSources?.length ?? 0) > 0 &&
otherSources.map((source, index) => {
return <SourceView {...source} index={index} key={`field${index}`} />
})
}
</div>
)
If I enter any character in any of input then focus moves away. Can someone please highlight what is the issue here?
Fix: I was using SourceView as a React component, which was causing it to rerender and the focus to move away. If I directly call SourceView() instead of focus stays.
3
Answers
Fix: I was using SourceView as a React component, which was causing it to rerender and the focus to move away. If I directly call SourceView() instead of focus stays.
There are some syntax errors in your code, but when you solve them it works and focus stay if you type in the input
See below what needs to be corrected
see codesandbox https://codesandbox.io/s/jolly-keldysh-bn1gbw?file=/src/App.js:23-412
try below solutions.