'React-routing v6 can't pass component props to mapStateToProps
I'm new to react and trying to make a simple project. My problem is I'm trying to pass component props to mapStateToProps and I can't do it. I read that i should pass ownProps to mapStateToProps as parameter however it is always empty.
<Routes>
<Route path="/" exact={true} element={<CollectionsOverview />} />
<Route path="/:id" element={<CollectionPage />} />
</Routes>
const CollectionPage = ({ collection }) => {
const { id } = useParams();
this.props.id = id;
const { title, items } = collection;
return (
<CollectionPageContainer>
<Title>{title}</Title>
<ItemsContainer>
{
items.map(item => <CollectionItem key={item['id']} item={item} />)
}
</ItemsContainer>
</CollectionPageContainer>
)
}
const mapStateToProps = (state, ownProps) => {
console.log(ownProps);
return {
collection: selectCollection(ownProps.id)(state)
}
}
ownProps is empty object here.My question is how can i pass properties to mapStateToProps or what am i doing wrong here
Solution 1:[1]
this.props.id does not exist on react functional components. You did it right by destructuring with useParams. But in ownProps you dont have a id property. So you cant pass it in selectCollection like that. You can have a look at this demo App. Hope it helps you understand how you could set all up.
import { useParams } from "react-router-dom";
import { connect } from "react-redux";
const CollectionPage = ({ collection }) => {
const { id } = useParams();
//this.props.id = id;
console.log(id);
const { title, items } = collection;
return (
<div>
<div>{title}</div>
<div>
{items.map((item) => (
<div key={item["id"]} item={item} />
))}
</div>
</div>
);
};
const mapStateToProps = (state, ownProps) => {
console.log(ownProps.collection.items[0].id); //this is how you can access an ID from your items
/* return {
collection: selectCollection(ownProps.id)(state)
} */
};
export default connect(mapStateToProps)(CollectionPage);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MWO |
