Hey, guys. In this video, we're going to talk about mixins, which are a really cool way to pass functionality into multiple components. To get us started, I'm going to go ahead and build up a quick app.
Let's see. We're just going to return a couple components here. I'm going to wrap this in a div. Our first component is going to be our Button, capital B Button component. It's going to have a prop of txt. Here, I'm just going to say "This is the button" and close that.
This next one's going to be a Label component. Our txt prop there is going to be "This is the label." I'm going to close that out. Let's go ahead and build up these components. Here's our Button, where it's going to output a button. We're going to pass that prop of txt in as its inner HTML.
We'll go ahead and create our Label. Same as the Button. This will be a label. Don't need the htmlFor. We'll just pass in the prop of txt as its inner HTML. Let's go ahead and render this out. I'm going to render App to the document.body. Let's go ahead and load that up. Let's go ahead and drop a line break right here.
Let's say on the componentWillMount phase of each of these components, I want it to go ahead and console.log something out. I'm going to create our mixin in order to do that. It's an object. I'm just going to drop in our componentWillMount phase right here. I'm going to console.log "Will mount."
To get this guy into each of our components, we're going to use the mixins key. That's an array. We just pass in the mixin or mixins that we want our component to inherit. I'm going to load that up. You can see we got "Will mount" two times.
We can also pass in any sort of custom functionality we might want to. I'm going to set an initial state with a count of zero. I'm going to create a custom method called "IncrementCount."
Here, we're just going to go ahead and update the state.count to plus one. Down here, on the button, we're going to output our state.count right here, next to our props.txt. We're going to call our increment method on the click of the button so onClick equals this.incrementCount. Let's go ahead and try that out.
Cool. We now have that functionality there, in our Button. Here, in our Label, let's say we're going to tap into that function in the componentWillMount phase. We technically are merging the mixins componentWillMount with our component componentWillMount.
I'm going to set an interval here to call this.incrementCount. We'll do that every second. We'll go ahead and output that the same as we did in the Button.
Load that up. We can see that the Label is incrementing in the set interval. The Button is updating that value in the un-click. Both of them have inherited the same functionality. We're able to use it as we see fit.