Home > Net >  How to access match inside mapStatetoProps
How to access match inside mapStatetoProps

Time:08-21

how can I access match inside map state to props

import React from "react";
import "./collectionpage.styles.scss";
import { connect } from "react-redux";
import { selectCollection } from "../../redux/shop/shop.selector";
import { useMatch } from "react-router-dom";
 
import Collectionitem from  "../../components/collection-items/Collectionitem.component";



const CollectionPage = ({collection}) => {

    const match = useMatch();
    const {title, items } = collection;
    return(
        <div className="collection-page">
            <h2 className="title">{title}</h2>
            <div className="items">
                {
                    items.map(item => <Collectionitem key={item.id} item={item}/>)
                }
            </div>
        </div>
    )
}


mapStatetoProps = (state) =>{
    return ({
        collection :selectCollection(match.params.colletionID)(state)
    })
} 

export default connect(mapStatetoProps)(CollectionPage);

CodePudding user response:

You can try as follow

...

     const mapStateToProps = (state, ownProps) => {
          return {
           collection: ownProps.match.params.colletionID
          }
     }
    
...

Here ownProps are the attributes that are passed when the component is used. In plain React these would be just called props.

CodePudding user response:

mapStatetoProps allow you pass owner props to. So you can pass match to a component. in this case is CollectionPage

const ComponentA = () => {
    const match = useMatch();
    return (<CollectionPage match={match}/>)
}

then:

const mapStateToProps = (state, ownProps) => {
      return {
       collection: ownProps.match.params.colletionID
      }
 }
  • Related