How to connect a React component to action creator
We have seen how to connect a component to an action creator through the connect
function made available by the React Redux library.
But connecting a component to an action creator is not enough. In order to actually trigger the action we need to listen to an event and fire up a function that calls the action creator that we have connected.
Since we passed the action creator to connect, this function is now available to the component through the props
.
Here's the relevant code we put at the bottom of our Title
component file:
export default connect(
() => {},
{ turnTitleGreen }
)(Title);
In this case, the action creator is turnTitleGreen
and we pass it to connect
inside the object in the second argument.
This syntax:
{ turnTitleGreen }
is equivalent to saying this:
{turnTitleGreen: turnTitleGreen}
So, we effectively created a property on this object. The property is called turnTitleGreen
and the value is the turnTitleGreen
function that was imported from actions/index.js
The connect
function sets things up so our Title
component now has a prop
called turnTitleGreen
, set to the value of the action creator.
This means that we can invoke the action creator like this:
this.props.turnTitleGreen();
and the action creator will be called, and will dispatch the appropriate action to the reducer.
How do we invoke turnTitleGreen
, though?
Let's say we want to turn the title green when someone clicks a button.
We add an event handler to the button with the onClick
property pointing to
a function in the component:
Here's the button:
<button onClick={this.handleTitleGreen}>Change title color</button>
Now we need to define handleTitleGreen
inside our component:
handleTitleGreen = e => {
e.preventDefault();
this.props.turnTitleGreen();
}
We have seen these types of functions before. First we prevent default, so the page won't be reloaded as a result of clicking the button.
Then we call the turnTitleGreen
function that lives on the props
.
This sends the TURN_TITLE_GREEN
action to the reducer and the reducer returns a new state object with the titleColor
property changed to 'green'
.
In Title
, the actual title is inside an h1
component. h1
has a style property with the text color set to the value of the titleColor
property on the state. When the reducer changes this property, the text color gets updated accordingly.
<h1 style={{ color: this.props.titleColor }} >
This is the title
</h1>
And with this we have come full loop: we click a button that triggers an event.
The event calls a function that calls an action creator.
The action creator dispatches an action that ultimately changes the title in our component.
I write daily about web development. If you like this article, feel free to share it with your friends and colleagues.
You can receive articles like this in your inbox by subscribing to my newsletter.
Top comments (0)