1

Now I'm doing 'dirty' split to get any id from the url. I'm not sure how to utilise react router, I did something like this

this.__isEdit = (this.props.history.location.pathname.indexOf('edit') > -1)

const pathnameArr = this.props.history.location.pathname.split('/')
this.__todoId = pathnameArr[pathnameArr.length - 2] //get second last arr

for one of my route

<Route exact path='/admin/ad/:id/edit' component={createTodoComponent} />

Anyway I can improve it the code?

Jenny Mok
  • 2,744
  • 9
  • 27
  • 58

2 Answers2

6

So for you component you'll need to wrap it with the withRouter method from 'react-router-dom' then you can get any of the params from this.props

import { withRouter } from 'react-router-dom'

const component = ({match}) => {
    const id = match.params.id

    return (
        <span>{id}</span>
    )
}

export default withRouter(component)

or if you want to do it with the React component class

import { withRouter } from 'react-router-dom'

class NewComponent extends Component {
    render() {
        const {match} = this.props
        const id = match.params.id

        return (
            <span>{id}</span>
        )
    }
}

export default withRouter(NewComponent)
Dale Francis
  • 537
  • 2
  • 10
0

react router params are available on this.props.params inside the connected component.

EMC
  • 1,560
  • 2
  • 17
  • 31