I am having trouble wrapping my head around the spread operator when used in the following context:
const renderField = ({input, label, type, meta: {touched, error, warning}}) => (
<div>
<label>{label}</label>
<div>
<input {...input} placeholder={label} type={type} />
{touched &&
((error && <span>{error}</span>) ||
(warning && <span>{warning}</span>))}
</div>
</div>
)
in this case, is it taking all the props and setting them as input.propname ?
Yes! When you spread input
, your component automatically gets its attributes.
Let's say your input
is:
const input = {
type: 'text',
value: 'new value',
placeholder: 'Type anything'
}
After spread, your rendered component is going to be:
<input type="text" placeholder="Type anything" value="new value" />
Youre using JSX in your components. If you look at the linked article, JSX is basically just a wrapper around React.createElement
. Whenever you're using braces in JSX, you're actually executing a regular JavaScript statement.
So, in your case, what actually happens (simplified) is the following:
React.createElement('input', {placeholder: label, ...input})
If your input
variable contains other props, like value
, then those props will be added to the original props object ({placeholder: label}
), as per the spread operator specification.
The spread syntax is also documented in the JSX explanation article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With