there are two components
- input – where the user will enter the value
- there is an output (H1) where this value will be displayed immediately
These two components are displayed in the parent file where they are as an array and are displayed in different places in html.
Also in the parent file, there is a button that creates 1 input and 1 output, which interact with each other and are independent of the rest of the same.
So far, the main problem is that two components display what I need when rendering, but do not change the value
Parrent
import InputTest from './InputTesting'
import TestOutput from './OutputTest'
const PageToCombine = () =>{
const [title, setTitle] = useState('qwrqw!')
const changeTitle = event => {
setTitle(event.target.value);
}
const [inputItems, setInputItems] = useState([
{id:32, type:"text", onchange:changeTitle, value:title},
])
const [outputItems, setOutputItems] = useState([
{id: 12, type:"text", value:title, onchange:changeTitle},
])
return(
<div>
{inputItems.map((inputitem) =>
<InputTest id={inputitem.id} type={inputitem.type} value={inputitem.value} onChange={inputitem.onchange}/>
)}
{outputItems.map(outputitem =>
<TestOutput id={outputitem.id} type={outputitem.type} value={outputitem.value} onChange={outputitem.onchange}/>
)}
</div>
)
}
TestOutput component
const TestOutput = (props) =>{
console.log(props)
return(
<div>
<h1 {...props} onChange = {props.onChange}>{props.value}</h1>
</div>
)
}
InputTest component
const InputTest = (props) => {
console.log(props)
return(
<input className={classes.inputTestStyle} {...props}/>
)
}
3
Answers
You’re on the right track to solving this problem, the key is to not pass a predefined
onChange
to the input but to generate one for each item. Thereby your parent is fully controlling your dynamic inputs.codesandbox demo
Notice that an
id
is used to identify each item, this is by React recommendations to not use indices as keys in case the items are reordered. That also means it’s up to you to generate a unique id.It looks like you try to use to many states you can just use one state for this
You are using too many states and seems like you are not updating inputItems by setting setInputItems you should do like this with only one state for inputTest component and testOutput component
Parent component
}
InputTest component
Outputtest component