joethemow
joethemow

Reputation: 1773

Add query parameters in link react-router

I am trying to add query parameters in my url, but having trouble. For visual sakes I put the Link object in the onSubmit, but I know that this is not allowed.

<form onSubmit={<Link to={{ pathname: '/me', query: { showAge: true } }}/>}>
 .....
</form>

Upvotes: 1

Views: 13952

Answers (2)

spedy
spedy

Reputation: 2360

I solved it by doing:

let clientId = 2;

this.props.history.push({
    pathname: '/client',
    search: "?" + new URLSearchParams({clientId: clientId}).toString()
})

or

this.props.history.push('/client?clientId=1')

I put the above code in a function and binded it in constructor so it has access to props and props.history in your case:

constructor(props){
    super(props)
    this.onSubmitClick = this.onSubmitClick.bind(this)
}

onSubmitClick(){
    this.props.history.push('/client?clientId=1')
}

and

<form onSubmit={this.onSubmitClick}>

</form>

You might also need to wrap your component in a withRouter decorator eg. export default withRouter(Component);

Upvotes: 0

Mayank Shukla
Mayank Shukla

Reputation: 104379

Use browserHistory/hashHistoryWrite.push(), to got to specific route, onSubmit call. Put all the values in query that you want to pass, like this:

onSubmit={()=>hashHistory.push({
                 pathname: '/me',
                 query: {a: "a", b: "b", "c": c}
              })
};

or

onSubmit={()=>browserHistory.push({
                 pathname: '/me',
                 query: {a: "a", b: "b", "c": c}
              })
};

Upvotes: 2

Related Questions