Reputation: 343
I have a list of things, When I click on a line, I retrieved the element ID from my list with my onClickDetail function
After that I would like to redirect the user to a new component passing this element ID How can I handle that ?
App.js route:
<HashRouter>
<Provider store={store}>
<Switch>
<Route exact path="/login" name="Login Page" component={Login} />
<Route exact path="/register" name="Register Page" component={Register} />
<Route exact path="/404" name="Page 404" component={Page404} />
<Route exact path="/500" name="Page 500" component={Page500} />
<PersistGate loading={null} persistor={persistor}>
<Route path="/" name="Home" component={DefaultLayout} />
</PersistGate>
</Switch>
</Provider>
</HashRouter>
Where I can click on my element (this.props.currentElement is an id) :
<td><i className="fa fa-edit fa-lg " style={{color: '#63c2de'}}
onClick={this.handleClick.bind(this, this.props.currentElement)}></i></td>
My onclick function :
handleClick = (currentElement) => {
console.log('list ref' , currentElemnt); // display my id ok
return (
<Link to={"/listDetail/" + currentElement}>my list detail id : {currentElement}</Link>)
}
I though adding in app.js
<Route path="/listDetail/:id" component={ListDetail}>
And add to my onClickDetail function
<Link to={"/listDetail/" + id}>my list detail id : {id}</Link>
But it's not working. Nothing Happen excepte the console.log
Maybe it's not the best way to do it, so I just wanted to know how to Handle OnClick to redirect my user to a new component passing props.
The story line should be :
Thanks a lot
Upvotes: 0
Views: 9190
Reputation: 2928
In the HomePage
component, as it is rendered from a <Route />
, it should receive the Router props such as match
and history
.
So, inside of your onClick
function, you will simply need to do something like
function onClick(id) {
this.props.history.push("/listDetail/" + id);
}
Upvotes: 2
Reputation: 2010
instead of using <Link/>
, you can use push method from history
node package.
Install history: npm install history
Create a file history.js:
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
export default history;
import history where you want to change your url.
Your onClick function: (url) => history.push(url)
;
import history where your router is:
<Router history={history} />
Try it this way :)
Upvotes: 1