Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    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.



    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




    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.

    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.

    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.

    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.

    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.

    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.

    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.