I’ve dived into so many examples, but still don’t understand why I’m getting this issue.
The problem is simple, I created a component modal and another one called input, which returns a label, an input field and an error message according to the validation provided. Whenever the input (inside the app function within the modal component) changes its value, it loses the focus as well. I’ve already defined keys for it, and understood that as the state that handles it is in its parent component, so that it changes the value, it re-renders. Nevertheless, how am I going to update the main state for all of the inputs needed outside the parent component? Because it seems that’s where the issue triggers.
The piece of the app where the state is created, the modal component and the input one.
import { useRef, useState, useEffect } from 'react'
import Modal, { ModalBody } from './Components/Modal';
import ModalText from './Components/ModalText';
import Input from './Components/Input';
import getUsers from './Requests/getUsers';
import { validateFields, handleChange } from '../Helpers';
import { formFields } from './Models';
import './App.css'
function App() {
// The form fields
const [inputFields, setInputFields] = useState(formFields('fields'));
const [emptyInputFields, setEmptInputFields] = useState(formFields('empty-fields'))
useEffect(() => {
getUsers(false, '', '', setUsers);
}, []);
console.log(inputFields);
return (
<div key={26142} className='container'>
<Modal
key={281}
show={openModal}
title="Edit User"
close={() => setOpenModal(false)}
>
<ModalBody key={27}>
<ModalText
kind={modalTextKind}
currentUser={currentUser}
/>
<Input
key={1}
label='Name'
type='text'
name='name'
value={inputFields.name}
placeholder="Full Name"
isInvalid={emptyInputFields.name}
state={setInputFields}
/>
<Input
key={2}
label='Age'
type='number'
name='age'
value={inputFields.age}
placeholder="How old is this one?"
isInvalid={emptyInputFields.age}
state={setInputFields}
/>
</ModalBody>
</Modal>
</div >
)
}
export default App
Here is the input component
import { handleChange } from '../../../Helpers';
import './input.css';
function Input(props) {
const { label, type, name, value, placeholder, isInvalid, state } = props;
function setState(e) {
handleChange(e, state);
}
const id = `${label}ID`;
return (
<div>
<label htmlFor={id}>{label}</label><br />
<input
type={type}
id={id}
name={name}
onChange={(e) => setState(e)}
placeholder={placeholder}
/>
{isInvalid &&
<div className="warn-aria-form" role="alert">
<i className='fas fa-exclamation-circle'></i>
<span>The {name} cannot be empty.</span>
</div>
}
</div>
)
}
export default Input
I’ve been thinking of using redux, is that the case?
Any help would be appreciated!