Set the HTML Tag of a Component via a Prop using Recompose

Tim Kindberg
InstructorTim Kindberg
Share this video with your friends

Social Share Links

Send Tweet

Learn how to user the ‘componentFromProp’ helper and ‘defaultProps’ higher order component to swap the underlying html tag of your component. Sometimes we want a component to behave the same overall but to use a different element in the HTML output. An example is swapping an <a> for a <button> or even a react router <Link> depending on circumstance.

[00:00] I have a little app with an anchor tag and a button. I want to create a generic link component, and I want it to be able to be either an anchor tag or a button based on a prop, but otherwise, I don't want the overall behavior of my link component to change just because the underlying element changes.

[00:18] I'll need to compose together a couple higher order components. I'll use width props to do some work. I'll provide a function to width props which receives the owner's props, and I'll destructure the type and the To prop off of there.

[00:34] Let's go ahead and set some defaults for these. I want the type to be A by default, and I'll have the To just be a hash symbol. Now I want to inspect the type, and if it's equal to A. I want to return a prop object that passes on the type and also converts the To to an HREF, because anchor tags navigate via the HREF attribute.

[01:08] If the type is not A, we can assume it's button. I'll still pass in the type again, and this time, I want to add an onClick handler. The button needs to redirect by setting the window.location. Now we'll apply all this to a component. This is where component from prop comes in.

[01:28] Component from prop is not a high-order component. It technically returns a component, but you don't pass a component. Instead, you pass it the name of the prop that you'd like to build the component from. In this case, I want to build a component that renders an element based on the type property that's coming in.

[01:49] Now, we can add a link. We can tell it to go to page one. Then we'll make this an anchor link, because we didn't provide a type. We can do another link that goes to page two. This one will send a type in, of button. We'll make it a button link.

[02:15] When I refresh, I have two anchor links and two button links, but the second two links use a consistent component interface. We don't care how it's going to do the navigation. All we specify is a To prop, and it just works. If we want to change the visual aspect, we change the type.