I want to capture the data in my UserInput component and bring it back to the App.jsx and store it in the state.
My investment object looks like
const [initialInvestment, setInitialInvestment] = useState({
initialInvestment: 100,
annualInvestment: 200,
expectedReturn: 3.3,
duration: 4
});
The object looks like
{
initialInvestment: 100,
annualInvestment: 200,
expectedReturn: 3.3,
duration: 4
}
My JSX code for the component UserInput.jsx
<div id={'user-input'}>
<div className={'input-group'}>
<div>
<label>Initial Investment</label>
<input type={'number'} defaultValue={investment.initialInvestment} onKeyDown={event => onInvestmentUpdate(event)} required/>
</div>
<div>
<label>Annual Investment</label>
<input type={'number'} defaultValue={investment.annualInvestment} onKeyDown={event => onInvestmentUpdate(event)} required/>
</div>
<div>
<label>Expected Return</label>
<input type={'number'} defaultValue={investment.expectedReturn} onKeyDown={event => onInvestmentUpdate(event)} required/>
</div>
<div>
<label>Duration</label>
<input type={'number'} defaultValue={investment.duration} onKeyDown={event => onInvestmentUpdate(event)} required/>
</div>
</div>
</div>
I need to lift the state from the UserInput and bring it to App.jsx
App.jsx
const investmentHandler = (investment) => {
//const newInvestment = [...initialInvestment, ...investment];
setInitialInvestment(prevInvestment => {
return {
...prevInvestment,
investment
}
});
}
<UserInput init={initialInvestment} onUpdate={investmentHandler}/>
2
Answers
UserInput.jsx
App.jsx
Here are fundamental data down/events up principles applied to your app as I understand it. I haven’t worked through all the details, but it gives you an idea how it should look.
One thing I’m not clear on is why you only have an event handler for one input, yet you seem to want to update the entire object in the app’s handler. I’d update object properties individually from specific form values, or just wait for the entire form to be submitted and do it all then.