How do I set default props for a component wrapped in a Raley container?

434 views Asked by At

I have a component wrapped in a Relay container:

const Widget = (props) => {
  return (
   <div> { props.foo.bar } </div>
  )
}

Widget.defaultProps = { foo: {bar: 0} }

export default Relay.createContainer(Widget, {
  fragments: {
     store: () => Relay.QL`
       fragment on WidgetData {
          foo {
             bar
          }
        }
        `
   }
})

I'm using a GraphQL-as-a-service provider for a backend, and when the foo property of WidgetData isn't present, it returns null, which throws when my component attempts to render props.null.bar

As far as I know, defaultProps only works when the prop is undefined, not when it's null.

How can I protect against null results with defaultProps in this case?

Hoping to avoid writing a guard statement for each prop I reference, if possible.

1

There are 1 answers

0
Fan Jin On

You can do a sanity check for props from Relay container.

render() {
  let {
    foo,
    ...other
  } = this.props;   
  let bar = foo ? foo.bar : '';
  return (
    <div> { bar } </div>
  )
}

For more info, checkout: https://github.com/bfwg/relay-gallery