Reputation: 5566
I have a simple modal in which I have a form on submit I display errors now I want to pass these errors to the children component.
Here is a simplified parent component
import React from 'react';
import Input from 'components/Functional/Input';
function Parent() {
const [errors, setErrors] = useState([]);
const handleSubmit = async e => {
const formData = new FormData();
}
return (
<Modal handleSubmit={handleSubmit}>
<Input setErrors={errors} ></Input>
</Modal>
)
}
export default Parent
Here is my children component
import React from 'react'
function Input({errors}) {
const [field, setField] =useState('');
console.log('errors', errors)
return (
<div>
<input type="text" onChange={e => setField(e.target.value)} />
</div>
)
}
export default Input
Now when I submit the data with errors, the console.log('errors', errors)
in the children component I get undefined
What is wrong here?
Upvotes: 0
Views: 194
Reputation: 105
You seem to have a typo in your input component. You set the prop setErrors
but your component expects errors
. If you use plain javascript you should use proptypes to ensure this doesn't happen.
import React from 'react'
import PropTypes from 'prop-types'
function Input({errors}) {
const [field, setField] =useState('');
console.log('errors', errors)
return (
<div>
<input type="text" onChange={e => setField(e.target.value)} />
</div>
)
}
Input.propTypes = {
errors: PropTypes.arrayOf(PropTypes.string)
};
export default Input
See PropTypes
Upvotes: 0
Reputation: 473
Pay attention to props name. You're passing from parent a property called setErrors
while in child component you're looking for errors
. Try to rename property from setErrors
to errors
or simply read setErrors
from <Input />
component
Upvotes: 1