Learn how to use the ‘withProps’ higher order component to pre-fill a prop, unable to be overridden.
[00:00] Let's say I wanted to keep all of the links from my application in one place. We'll define a home link. The base component for my home link is going to be an anchor tag. I'd like to enhance this by using the withProps higher-order component from Recompose. I need to supply withProps a prop object. I'll pass in href.
[00:25] I want it to always be set to the root URL of my application. I'm going to create a "Products" link as well, and a "Checkout" link. Now, I can replace both of these anchor tags that were going to the same place with just one home link. If home link were ever to change its URL, I'd only have to change it in one place.
[01:04] Next, I can change the "Products" link and the "Checkout" link. Notice how the text between the links is still provided. I only want the behavior of the link to be the same, not the link text. When I refresh, everything still works the same.
[01:23] The text in the link still shows up because withProps does not clobber the props that you passed in. It simply merges the props that we supply with any props that may have been passed in. That includes the prop children.
[01:38] This line is equivalent to writing it like this. We could write a functional stateless component that returned an anchor tag where the href is set to the root, and then we put the children in the middle.
[01:56] By using withProps, you don't have to worry about where the children are going to go. It'll just work. WithProps can also accept a function instead of an object. If you provided a function, then you need to return an object.
[02:10] The function will take in the owner props. For example, we could add a query prop to our home link. We could specify that the logo is clicked in case we need it to track it for metrics, and provide that to the href.