dev1
dev1

Reputation: 83

react component props does not have match

I'm using react-routing-dom V5 in my react project. I need to pass props from App component (where I import Router) to child component through protected route. The problem is that props is empty, does not have match, location, history..

**App Component

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'

class App extends Component {
  render(){
    console.log(this.props); //props does not have match propreties
    return (
    <div className="App">
        <Router>
          <React.Fragment>
            <Switch>
             <ProtectedRoute path='/exemple' component={Exemple}/>
             </Switch>
          </React.Fragment>
        </Router>
    );
 }
}

NOTE: I pass props from App to child component where i need to use this.props.match, but match is undefinded

Upvotes: 0

Views: 3180

Answers (4)

Cesar Moran
Cesar Moran

Reputation: 153

In a component that isn't routed you should use:

import { useParams, useHistory } from 'react-router-dom'

const history = useHistory()

const { keyword, id, whateverTheParamIs } = useParams()

Upvotes: 0

Mohammed Al-Reai
Mohammed Al-Reai

Reputation: 2806

of course, it shouldn't have match object A match object contains information about how a matched the URL. way to access the match object from

Route component as this.props.match
Route render as `({ match }) => ()`

Route children as ({ match }) => ()

`withRouter` as this.props.match

Upvotes: 0

ANIK ISLAM SHOJIB
ANIK ISLAM SHOJIB

Reputation: 3248

try this

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'

class App extends Component {
  render(){
    console.log(this.props); //props does not have match propreties
    return (
    <div className="App">
        <Router>
          <React.Fragment>
            <Switch>
<Route
  path='/dashboard'
  render={(props) => <Dashboard {...props} isAuthed={true} />}
/>
             </Switch>
          </React.Fragment>
        </Router>
    );
 }
}

Upvotes: 0

Fernando Montoya
Fernando Montoya

Reputation: 2644

match props is only available to components of a route:

<Route exact path="/foo" component={({ match }) => console.log(match)} />

If you need it on App, you need to create a route for App.

Upvotes: 2

Related Questions