I have a parent component which maps through my array and prints out various iterations of my Child components.
I'm trying to access the state in the parent component but can't figure out how to lift the correct state of "inputValue" from the child and have it in the parent instead.
Ideally I'd like the inputValue and isValidated state living in the PARENT so I can use it for various form-based functions.
Parent Component:
import React, { useState } from 'react';
import { formFieldsData } from './FormFields';
import Input from './Input';
export default function Form() {
return (
<form>
{formFieldsData.map((item) => (
<Input
key={item.id}
id={item.id}
label={item.label}
type={item.type}
placeholder={item.placeholder}
/>
))}
</form>
)
}
Child component:
import React, { useState } from 'react';
import styles from './forms.module.scss';
import RangeInput from './RangeInput';
export default function Input({ type, id, placeholder = '', label, props }) {
const [inputValue, setInputValue] = useState('');
const [isValidated, setIsValidated] = useState(false);
const isRangeInput = type === 'range';
const handleChange = (e) => {
setInputValue(e.target.value)
if(inputValue.length > 0 || type === 'date') {
setIsValidated(true)
}
}
return (
<div className={styles.form__row}>
<label htmlFor={id}>{label}: {inputValue}</label>
{isRangeInput
? <RangeInput id={id} onChange={(e) => handleChange(e)} />
: <input
required
type={type}
id={id}
name={id}
placeholder={placeholder}
className={styles.input}
value={inputValue}
onChange={(e) => handleChange(e)}
/>
}
<button type="submit" id="formSubmit" onClick={() => alert('button click catched')} disabled={!isValidated}>Submit!</button>
</div>
)
}