ReactJS ‘getDefaultProps’ & ‘propTypes’
So maybe it’s a relatively obscure React lifestyle event, but I finally found a practical use for `getDefaultProps`, so that’s cool.
Basically, getDefaultProps allows you to give your component some props which can be overridden, but in case none are given to the component somewhere else in your code, you’ll have some defaults in there.
Let’s say you have a component that uses a breakpoint to show something up until a certain screen width and shows something else at another. You can set breakpoint as a default prop in your component at, for example, 500px to make sure your code operates as desired.
But in another place in your code, you decide you need a different breakpoint set for a particular part. You can set a new breakpoint and pass it in as a prop which will override the default setting.
Get Dan Buda’s stories in your inbox
Join Medium for free to get updates from this writer.
Setting a default breakpoint of 500:
And then on the parent component, after importing the component above (lets call it “Child”) you can pass in props to override the default:
Additionally, you can go back to the Child component and tell it what the breakpoint prop should look like with propTypes:
propTypes can be any number of things: string, bool, number and more.
So there it is. A way to set some default props for a component while being able to easily override them if need be.









