Search code examples
javascriptreactjsspread-syntax

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} />

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