Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router params returning empty object

In my App.js file where I render all my routes I have this code:

import LiveMatch from "../containers/LiveMatch";

const routes = [
  //removed other routes for simplicity of post
  {
    path: "/livematch/:matchid", <--- here is the param I want
    exact: true,
    component: () => <LiveMatch />
  }
];

class App extends Component {

  render() {
    return (
      <div>
        <BrowserRouter>
          <div>
            {routes.map((route, index) =>
              <Route
                key={index}
                path={route.path}
                exact={route.exact}
                component={route.component}
              />
            )}
          </div>
        </BrowserRouter>
      </div>
    );
  }
}

Now that I have the component set up, I try to print out the :matchid parameter but I keep getting an empty object.

class LiveMatch extends Component {
  constructor(props) {
    super(props)
    this.state = {...}

    console.log(this.props) // returns { }
  }

  componentDidMount() {
     console.log(this.props) // returns { }
  }

}

Whether I try to access props in constructor or after mounting the props is always empty. From other posts I've searched up apparently the answer should be as simple as this.props.params.matchid or this.props.match.params.matchid.

Question: How do I get access to the :matchid param. Am I doing anything incorrectly?

like image 993
Phillip Avatar asked Sep 01 '17 08:09

Phillip


1 Answers

Why it is not available inside LiveMatch component?

Because you are not passing the default props (means props passed by router into component) into LiveMatch component. You are overriding the props values.

Solution is, With arrow function receive the props and pass down into component it will work.

Write it like this:

component: (props) => <LiveMatch {...props}/>

Or remove the arrow function:

component: LiveMatch
like image 185
Mayank Shukla Avatar answered Nov 04 '22 02:11

Mayank Shukla