neowenshun
neowenshun

Reputation: 960

How to pass params into history push

I have a click handler here that is supposed to help me redirect the page upon clicking the item in the list.

Expectations:

onRowClick: (rowIndex) =>this.props.history.push( {pathname: '/tickets',  param: rowIndex[0]};

Of course however, the code won't work. rowIndex is the param that I wish to pass into the url.

this is the history as logged in my console:

action: "POP"
block: ƒ block(prompt)
createHref: ƒ createHref(location)
go: ƒ go(n)
goBack: ƒ goBack()
goForward: ƒ goForward()
length: 50
listen: ƒ listen(listener)
location: {pathname: "/tickets", search: "", hash: "#/", state: undefined}
push: ƒ push(path, state)
replace: ƒ replace(path, state)
__proto__: Object

Here is what I have tried:

onRowClick: (rowIndex) =>this.props.history.push({pathname: '/tickets' , id: rowIndex[0]})

however there doesn't seem to have an effect upon clicking

Upvotes: 8

Views: 38630

Answers (5)

Krishnamoorthy Acharya
Krishnamoorthy Acharya

Reputation: 4254

We can pass URL params in below format

 history.push({
  pathname: '/some-path',
  search: '?q=india&id=12345'
 })

Upvotes: 2

Ajeet Shah
Ajeet Shah

Reputation: 19863

Alternatively, if you don't want to show your data in the URL, you can pass it in state:

this.props.history.push('/tickets', { data: rowIndex[0] })

or

this.props.history.push({
  pathname: '/tickets',
  state: {
    data: rowIndex[0],
  },
})

And in the Component, to get the data:

const data = this.props.history.location.state?.data

Read more: react-router and history

Upvotes: 15

Thanveer Shah
Thanveer Shah

Reputation: 3333

Why don't you simple fetch the param ID using match.

Example:

Your Route

<Route path="/tickets/:id" component={Tickets} />

onClick

this.props.history.push(`/tickets/${rowIndex[0]}`);

And then in the Tickets Component, fetch the param Id using match

Tickets Component

console.log(this.props.match.params.id)

Upvotes: 7

Abhijith v
Abhijith v

Reputation: 364

You can use 'useHistory' from the library 'react-router-dom'if using functional component.

First initialize as below.

 const history = useHistory();

Then you can call whenever wanted

history.push('Path')

For example when clicking a button

onClick{()=>{history.push('/ticket')}}

Upvotes: 1

Hamza Khattabi
Hamza Khattabi

Reputation: 674

try : this.props.history.push('/tickets', rowIndex[0]): the syntax should be : push(route, params)

Upvotes: 2

Related Questions