This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Lock Props by using the Recompose withProps Higher Order Component

    Tim KindbergTim Kindberg

    Learn how to use the ‘withProps’ higher order component to pre-fill a prop, unable to be overridden.

    reactReact
    ^16.0.0
    recomposeRecompose
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss