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.


    Make Reusable React Props Streams with Lenses

    John LindquistJohn Lindquist

    If you hard-code a stream of props to target a specific prop, it becomes impossible to reuse that stream with any other components. Configuring your props stream with lenses will allow you to reuse your stream with any React component.



    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




    Instructor: Install Ramda, and we'll import everything as r from Ramda. Now, we can use Ramda's lenses -- I'm going to call this personNameLens -- to target the path of the property I want to view or change. There's the person name, and that path is talking about right there.

    We'll say typewriter is a function that takes a lens and returns that function, meaning that now, in my typewriter, when I invoke it, I can pass in my personNameLens and get back that same stream. Now, all we have to do is use the lens here.

    I'll view the props through that lens, so lens props, which is essentially saying take the props and look at it through this lens. We can do a similar thing down here. Instead of person, and spreading out the person and assigning the name, we can do r.setLens.

    We want to set the name on those props, and that returns the entire props object with that name set on this path, which means I can also get rid of this, this, this, and format it. Now, it behaves the same way. If I go up, you see the typewriter is still working.

    If I create a date display component, which takes props and returns an h1 with, then I take a date typewriter, which will use my typewriter function, I'll invoke it. I'll create the lens in a second, but then I'll pass in the date display.

    Now, I create my lens. I'll call this a date lens, r.lensProp. I don't need a path, since it's just going to be one level deep. I'll say date, pass in my date lens. I'll declare my date typewriter down here, pass in a prop of the date, which'll be a new date, to date string.

    I'll hit save, and you'll see the date is being printed out with that typewriter. This typewriter is looking at the props through the lens of just the date prop. This date will come on through. This will view it and set it inside of this function, and then pass it onto the date display.