skip to Main Content

Hi i am new to React and javascript development and would like to know the difference between

var a = { className: 'my-secondary-classname' }; 
<span className="my-span-classname" {...a}>abc</span>

and

var a = { className: 'my-secondary-classname' }; 
<span {...a} className="my-span-classname">abc</span>

Tried reading about spread props and still not clear about it

2

Answers


  1. className is a prop. SO if you do {...a} and a is an object that contains className as a property, the value of a.classname will be applied to that component.

    If you do className before {...a}, a.className will override the previously supplied classname.

    If you do className after {...a}, className will override a.className

    const myClass = () => {
        let a = { className = "w-full bg-red", key: 1 };
    
        return (
            <div>
               <p {...a} className="bg-blue">Hello world</p> {/* this will have a blue background */}
               <p className="bg-blue" {...a} >Hello world</p> {/* this will have a red background */}
            </div>
    }
    
    Login or Signup to reply.
  2. The spread operator here is no different to a spread on an object, as that’s what your doing.

    So the spread will evaluate from left to right, so everything to the right will take precedence.

    eg..

    const a = {test: '123', other: 'other'};
    
    console.log({...a, test: '321'});
    console.log({test: '321', ...a});

    Notice how the first spread, we get ‘321’, and the second one it keeps the ‘123’.

    To prove this is just the same as spreading an object, here is what the JSX for your first one looks like ->

    "use strict";
    var a = { className: 'my-secondary-classname' };
    React.createElement("span", Object.assign({}, a, { className: "my-span-classname" }), "abc");
    //Note Object.Assign, is the alternative to using spread on older browsers
    //So the above is also the same as.
    React.createElement("span", {...a,className: "my-span-classname"}, "abc");
    
    

    So internally that JSX just gets converted into a Object.assign() -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

    Properties in the target object are overwritten by properties in the
    sources if they have the same key. Later sources’ properties overwrite
    earlier ones.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search