Managing Props as Component Developer

One of the little things one would have in mind when developing Components using React is that you might wonder if the developer who would consume the compoenent would pass in the required props.

Let us consider a simple component here.

export Navbar extends Component{
    render (<div><h1>{this.props.title}</h1</div>)
}

The above Navbar components expects the props to contain title, however, the Developer who would use it might not be aware of it and could forget supplying the same.

PropTypes

One of the ways to deal with it is using the PropTypes. This allows you to leave warnings for the developer regarding the props needed in the componenet. For example,

static propTypes = {
title: PropTypes.string.isRequired
};

The IsRequired flag raises console warnings for the developer each time he misses passing them when using the component.

DefaultProps

The other, but often less used approach is providing our default props, in case the developers ommits them accidentaly. This could be done using the defaultProps. For example,

static defaultProps = { title : 'Default Finder'}

Now if the developer forgets to add the props, the default ones would be used by the component. In case the developer adds them, the default ones would be overriden.

I guess you would need a bit of both (depending on the component requirement) to bring a balance to the approach.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s