user2456977
user2456977

Reputation: 3964

React defaultProps not working as expected

By default I want my lastMessage prop to be an object with an id. But with the code below it comes up as null.

Code:

const App = ({ lastMessage }) => { // lastMessage is currently null

    return (
        <Message lastMessage={lastMessage} />
    )
}

class Message extends Component {

    constructor(props) {
        super(props)
    }

    componentWillReceiveProps(nextProps) {
        const data = [];

        if (nextProps.lastMessage.id !== this.props.lastMessage.id) {
            log.debug('woohoo');
            // do something ...
        }
    }

    render() {

        return (
            // something...
        );
    }
}

Message.defaultProps = {
    lastMessage: {
        id: 0,
    },
};

In my App component I pass lastMessage as null to Message component. But I set defaultProps in Message component :

Message.defaultProps = {
    lastMessage: {
        id: 0,
    },

I expect lastMessage to be an object with an id, however it is still null. Then my app crashes because nextProps.lastMessage.id doesn't work if lastMessage is null

Even stranger if I remove the lastMessage prop in my App component:

const App = () => {

    return (
        <Message />
    )
}

Then the Message component creates the lastMessage defaultProp as an object with an id.

If my prop is null I am trying to pass it with a default value. I tried something like this but it still does not work:

const App = ({ lastMessage = { id: 0 } }) => { // lastMessage is still null

    return (
        <Message lastMessage={lastMessage} />
    )
}

Am I not setting the defaultProps correctly?

Upvotes: 0

Views: 4773

Answers (1)

Daniel
Daniel

Reputation: 18672

If you pass null to Message component you basically overwrite default property - lastMessage. If I understood you correctly then it works when you remove passing lastMessage to Message component. It should stay this way.

You can do ternary truthiness check before passing argument to component:

<Message lastMessage={lastMessage ? lastMessage : undefined} />

As you've also figured out you can also pass default props this way:

<Message lastMessage={lastMessage ? lastMessage : { id: 0 }} />

Upvotes: 2

Related Questions