Reputation: 53
Is there any way to remove the query string from the url in react application?
this.history.push('component/:id')
I want id to be removed from the browser url while navigation.
Upvotes: 4
Views: 12374
Reputation: 687
This is only suggestion: if you are using redux then save your id: in reducer then push any dummy string into your URL it will appear
import React, { Component } from 'react';
import { connect } from 'react-redux';
class example extends Component {
componentDidMount() {
if (this.props.match.params.id != 'dummy-string') {
this.props.saveId(this.props.match.params.id);
this.props.history.push('/component/dummy-string');
}
}
render() {
return (
<div >
<h1>Example</h1>
{this.props.id ?
<div>this.props.id</div>
:null}
</div>
);
}
}
const mapStateToProps = state => ({
id: state.reducer1.id
});
const mapDispatchToProps = dispatch => ({
saveId: (id) => dispatch({ type: 'SAVE_ID',payload:id })
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(example);
Upvotes: 0
Reputation: 3098
The Redirect
and Link
components both have an overloaded to
prop which can either be the string like you displayed above or an object with the following keys: pathname
, search
, hash
, state
. So your Link
can become something like
<Link to={pathname: '/component', state: {id: '#id'}} />
However, keep in mind that you will have to modify your Route to no longer require an id as a urlParameter and instead in your component you should use this.props.location.state.id
to access the variable.
Upvotes: 5