Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the way to pass object short-hand as props into React component?

Tags:

reactjs

jsx

What is the way to pass object short-hand as props into React component to reduce redundant repetition of same named key-pairs?

Here’s a sample of something I want to avoid:

const Comp = ( {a, b, c, d} ) => {
    return (
        <div>
            <SubComp
                a={a}
                b={c}
                d={d}
            />
           <AnotherSubComp
                a={a}
                c={c}
            />
        </div>
    ) 
}; 

Something I want:

const Comp = ( {a, b, c, d} ) => {
    return (
        <div>
           <SubComp {a, c, d} />
           <AnotherSubComp {a, c} />
        </div>
    ) 
}; 

Spread operator is not an option here, and creating an intermediate object is not reducing additional code at all.

like image 747
Bogdan Slovyagin Avatar asked Oct 21 '25 03:10

Bogdan Slovyagin


1 Answers

you can use the spread operator here like this:

const Comp = ( {a, b, c, d} ) => {
    return (
        <div>
           <SubComp {...{a, c, d}} />
           <AnotherSubComp {...{a, c}} />
        </div>
    ) 
}; 
like image 134
pwolaq Avatar answered Oct 23 '25 18:10

pwolaq