Search code examples
reactjsreact-reduxreact-router-dom

How to use useParams in mapStateToProps?


I want specific prop from route params and use it to filter data in redux-store.

Product.js

import React from 'react';
import { useParams } from 'react-router-dom';
import { connect } from 'react-redux';

const Product = (props) => {
    let { slug } = useParams();
    //console.log(props.match)
    return (
        <div>
            <h3>Welcome to <b>{ slug }</b> page</h3>
        </div>
    )
}

const mapStateToProps = ( state, ownProps  ) => {
    // let id = slug;

    return { item: state.items[0]}
}

export default connect(
    mapStateToProps
)(Product);

App.js

function App() {
  return (
    <Router>
      <Navbar/>
      <Switch>
        <Route exact path="/:slug">
          <Product/>
        </Route>
        <Route exact path="/">
          <Home/>
        </Route>
      </Switch>
    </Router>
  );
}

and whatever links that navigate to /slug path are ended up in Product.js, Since Product.js is being nested nowhere else so i couldn't get specific props pass down but route params. From my perspective this is completely wrong but i couldn't figure out a better way to do it.


Solution

  • Since you are using the new version of React and Redux. You can try use Hook to get data from redux store.

    Better call useSelector instead. Read more here

    import React from "react";
    import { useParams } from "react-router-dom";
    import { useSelector } from "react-redux";
    
    const Product = () => {
      let { slug } = useParams();
    
      const item = useSelector((state) => state.items[slug]);
    
      console.log(item);
    
      return (
        <div>
          <h3>
            Welcome to <b>{slug}</b> page
          </h3>
        </div>
      );
    };
    
    export default Product;