Make Reusable React Props Streams with Lenses

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet

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.

Instructor: [00:03] 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 props.person.name right there.

[00:30] 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.

[00:49] 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.

[01:11] 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.

[01:43] If I create a date display component, which takes props and returns an h1 with props.date, 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.

[02:04] 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.

[02:27] 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.