'How to set React default props for object type

We already know, how to set a defaultProps.

TestComponent.defaultProps = {
    isTest: true
};

But I often used props as object type.

In Parent,

render(){
    let sample = {
        isTest : true,
        isLoggedIn : true
    }
    return (
        <div>
            <TestComponent sample = {sample} />
        </div>
    )
}

In child component, I want to set isLoggedIn to false as default. If not set (or not passed from Parent) isLoggedIn, default value is true

But I don't know how to set defaultProps for object type

TestComponent.defaultProps = {
    sample : {
        isLoggedIn: false
    }
};

How to do this ?



Solution 1:[1]

Your code

TestComponent.defaultProps = {
  sample : {
    isLoggedIn: false
  }
};

should work.

And for type validation (propTypes), use React.PropTypes.shape for nested object props like this:

React.PropTypes.shape({
  isLoggedIn: React.PropTypes.bool
})

See the document: https://facebook.github.io/react/docs/typechecking-with-proptypes.html#react.proptypes

Solution 2:[2]

I think I had the same situation, and solved like below (it doesn't look like the best solution, but it's working):

const defaultSample = {
    isLoggedIn: false,
    isTest: true
}
let { sample = defaultSample } = props; // if doesn't have a sample, it will receive the default, if it does, will just receive the sample past by its parent
sample =  { ...defaultSample, ...sample } // first receive the default properties, than the sample to replace the existed default..

Solution 3:[3]

If I had 50 reputation I would have just commented on Breno Oliveira's answer, which I used successfully with slight modifications. Thanks Breno!

function TestComponent(props)
{
    let propsSample = {...props.sampleDefault, ...props.sample};
    const [isLoggedIn,setIsLoggedIn] = useState(propsSample.isLoggedIn);
    ...
}

TestComponent.defaultProps = {
    ...
    sampleDefault: {
        isLoggedIn: false
    }
}

As @mayid says in the comments of @CodinCat's answer, if the 'sample' object is passed into the props then the defaultProp values for sample will not be applied.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CodinCat
Solution 2
Solution 3 romehu2