fatima mukhtar
fatima mukhtar

Reputation: 23

this.props.match.params is empty even when passing params

I'm trying to pass params to this.props.match in my React component but even after passing I still got params as empty object.

render() {
  return (
    <div>
      <div className="boxx">
        {this.state.data.map(ele => (
          <div className="smallbox" key={ele.id}>
            <Link
              to={`${this.props.match.url}/movie1`}
              onClick={() => this.fetchOneMovieData(ele)}
            >
              <img
                src={`http://image.tmdb.org/t/p/w185${ele.poster_path}`}
                alt="movie pic"
              />
            </Link>
          </div>
        ))}

        <Route
          path={`${this.props.match.url}/:topicId`}
          render={props => (
            <OneMovie
              {...props}
              data={this.state.data}
              moviedata={this.state.moviedata}
            />
          )}
        />
      </div>
      {console.log(this.props.match)}
    </div>
  );
}

Upvotes: 0

Views: 8878

Answers (1)

Jack O&#39;Neill
Jack O&#39;Neill

Reputation: 1081

You have to use a Router and withRouter(), to access props.match

For example you can use a BrowserRouter and withRouter from react-router-dom like this:

App.js:

import MyComponent from "./MyComponent";
import {BrowserRouter, Route} from "react-router-dom";

class App extends Component {
    render() {
        return (
            <div className="App">                    
                <BrowserRouter basename='http://localhost:3000'>
                    <Route exact path='/:myparam' component={MyComponent}/>
                </BrowserRouter>
            </div>
        );
    }
}

export default App;

and MyComponent.js:

import {withRouter} from "react-router-dom";

class MyComponent extends React.Component {

    render() {
        console.log('props match', this.props.match);
        return <h1>MyComponent</h1>
    }
}

export default withRouter(MyComponent);

Visiting http://localhost:3000/asdf on the app from above leads to the console output:

props match Object { path: "/:myparam", url: "/asdf", isExact: true, params: {…} }

you can then access the value of :myparam on this.props.match.params.myparam, which gives you in this example:

asdf

Upvotes: 5

Related Questions