Home > front end >  Destructuring and Redefining react prop
Destructuring and Redefining react prop

Time:10-02

I've got a chunk of code at work that is behaving poorly and I am trying to figure out why. In the course of doing that, I came across something like the code below and I have some questions.

A functional component ...

const myComp = ({propName1, propName2: myVar = false})=>{
    ...
    const propName2=true;
    ...
}

I'm not totally sure what's happening with propName2 here. If there was just an "=false", then this would be establishing a default value, but that isn't what's happening. myVar is a variable that may be present as a prop. Is it simply setting the default value to that prop if it is present and false if not?

Second, why doesn't react produce an error when the code redefines the prop to a const?

Thanks

CodePudding user response:

This syntax is assigning propName2 prop to a myVar variable in the context.

This is roughly the same code:

const myComp = (props) => {
    let myVar = props.propName2;
    const propName2=true;
    ...
}

…so: this is why you don't get any error by defining propName2: it does not exists.

  • Related