mapStateToProps for functional component
You should connect
the component to the store at first.
The connection happen using the connect
HOC provided by the react-redux
package. The first paramter it takes, is a method that, given the global store, returns an object with only the properties you need in this component.
For instance:
import { connect } from 'react-redux'
const HelloComponent = ({ name }) =>
<p>{ name }</p>
export default connect(
globalState => ({ name: globalState.nestedObject.innerProperty })
)(HelloComponent)
To improve readability, it is common use the method mapStateToProps
, like this:
const mapStateToProps = state => ({
name: state.nestedObject.innerProperty
})
export default connect(mapStateToProps)(HelloComponent)
With Hooks you can use something like this
import React from 'react';
import {useDispatch, useSelector} from "react-redux";
const AccountDetails = () => {
const accountDetails = useSelector(state => state.accountDetails);
const dispatch = useDispatch();
return (
<div>
<h2>Your user name is: {accountDetails.username}</h2>
<button onclick={() => dispatch(logout())}>Logout</button>
</div>
);
};
export default AccountDetails;
react-redux now has a useSelector method. That's a much cleaner approach for functional components that employ hooks. See: https://react-redux.js.org/next/api/hooks#useselector
You can definitely use mapStateToProps
with a functional component, the same way you would with a class component.
function MyComponent({ propOne }) {
return <p>{propOne}</p>
}
function mapStateToProps(state) {
return { propOne: state.propOne };
}
export default connect(mapStateToProps)(MyComponent);