Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass properties but make exceptions in React

There is something common that sometimes we all do. Wrap dom elements in custom components

<CustomComponet id="abc" title="abc" nonDomProp="abc" ...andsoforth />

Custom component in this example wraps button which has the properties id and title but not nonDomProp so I get a warning which makes sense because nonDomProp doesn’t exist in the wrapped button DOM element and I am just passing all props to the button DOM element with the spread operator <button {...props} />

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

One way to solve this is by manually passing only the props that button will use, but I was wondering if there is a way to tell the spread operator to use all the passed ...props but to ignore nonDomProp.

I have tried to do a Google search and I have not been able to find what I am looking for so I thought maybe SO would point me in the right direction.

>Solution :

You can destructure the props object with this:

const { nonDomProp, ...propsButton } = props;
return(
 <button {...propsButton} />
)

Or directly from the argument of the CustomComponent function:

const CustomComponent = ({ nonDomProp, ...props }) => {
...
return(
 <button {...props} />
)
}

Docs: https://github.com/tc39/proposal-object-rest-spread#rest-properties

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading