Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spread operator in component react [duplicate]

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 ?

like image 596
snowflakekiller Avatar asked Dec 23 '22 14:12

snowflakekiller


2 Answers

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" />
like image 195
mersocarlin Avatar answered Dec 31 '22 03:12

mersocarlin


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.

like image 35
Oskar Avatar answered Dec 31 '22 02:12

Oskar