Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set React default props for object type

Tags:

reactjs

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 ?

like image 689
Junho Park Avatar asked Feb 10 '17 08:02

Junho Park


People also ask

How can you set default props on React component?

You can use props to send data to a component. Like default values for function arguments, props also have default values. defaultProps can be defined as a property on the component class itself to set the default props for the class. defaultProps is used for undefined props, not for null props.

How do you declare a default prop?

You can define default props this way: export class Counter extends React. Component { constructor(props) { super(props); this. state = {count: props.

Is defaultProps deprecated?

As per this tweet, defaultProps will eventually be deprecated.

Can a React prop be an object?

React props can be accessed as an object or destructuredOr they can be destructured, since props will always be an object, into separate variables.


1 Answers

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

like image 132
CodinCat Avatar answered Oct 15 '22 11:10

CodinCat