Skip to content Skip to sidebar Skip to footer

Mapstatetoprops For Functional Component

Is there any function similar to mapStateToProps so that we can connect Redux state to the functional component in React? Is passing the state as props from parent component the on

Solution 1:

You can definitely use mapStateToProps with a functional component, the same way you would with a class component.

functionMyComponent({ propOne }) {
  return<p>{propOne}</p>
}

functionmapStateToProps(state) {
  return { propOne: state.propOne };
} 

exportdefaultconnect(mapStateToProps)(MyComponent);

Solution 2:

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

Solution 3:

With Hooks you can use something like this

importReactfrom'react';
import {useDispatch, useSelector} from"react-redux";

constAccountDetails = () => {

    const accountDetails = useSelector(state => state.accountDetails);
    const dispatch = useDispatch();

    return (
        <div><h2>Your user name is: {accountDetails.username}</h2><buttononclick={() => dispatch(logout())}>Logout</button></div>
    );
};


exportdefaultAccountDetails;

Solution 4:

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'constHelloComponent = ({ name }) =>
    <p>{ name }</p>exportdefaultconnect(
    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
})

exportdefaultconnect(mapStateToProps)(HelloComponent)

Solution 5:

constCategoryList = (props) => {
    
      return (
           <div><h3>Category</h3><h5>Seçili Kategori:{props.currentCategory.categoryName}</h5></div>
      );
   }

    functionmapStateToProps(state) {
    
        return {
            currentCategory: state.changeCategoryReducer
        }
    }
    
    exportdefaultconnect(mapStateToProps)(CategoryList);

Post a Comment for "Mapstatetoprops For Functional Component"