destructuring props with the rest properties

Robbie Milejczak

so as I understand it, this {...props} is the same things as {prop1, prop2, prop3}

When declaring a stateless functional component, it is convenient to utilize destructuring so that you don't have to constantly type props.prop1, props.prop2 etc. However, when you have 10+ props you need to pass down to your child component things can get very ugly so I thought that I could just use the spread operator to destructure my props object!

Based on the idea that {...props} is essentially the same as {prop1, prop2, prop3} I expected the below code to work, but I get a prop1 is undefined error

const Component = ({...props}) => {
    return (
        <div>
            {prop1}
        </div>
    )
}

is what I'm trying to do possible? I couldn't find any examples online, but it would be awesome if there was a way to destructure the props object without explicitly listing every prop!

EDIT: Please understand I know how to properly access properties from the props object. Read my question more carefully, I am trying to spread all the properties in the props object, similar to declaring them explicitly example:

const Component = ({prop1, prop2, prop3}) => {
    return (
        <div>
            {prop1}
        </div>
    )
}

I expect that could to behave the same as if I initialize the component with {...props}

Mark C.

this {...props} is the same things as {prop1, prop2, prop3}

This is only true if you your function parameters deconstruct the object's properties by key value.

What I mean :

const doAThing = ({ prop1, prop2, prop3 }) => { console.log(prop1) }

And then calling it like doAThing({...props}) (where prop1 is a property on the props object) - In this scenario, you'd be correct. This is how it would work.

The reason you can't access prop1 like you're attempting to is because you haven't given the deconstruction assigment anything to assign to. It's just sitting there as the Object with the key/value pairs of prop1, prop2, prop3 etc..

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related