I'm creating a simple react app. I need to load a component from a button click. When I click the edit
button I need to load the edit component. I tried it using <Link>
. But I can't understand how to give the relative path. It means it need to load it like http://localhost:3002/viewTicket/603c9a02a2ccd501f45f820e/edit
. I need to load it from http://localhost:3002/viewTicket/603c9a02a2ccd501f45f820e
. How can I give the relative path?
App.js
<Provider store={configureStore()}>
<BrowserRouter>
<div className="App">
<LayoutWrapper>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/viewTicket/:id" exact component={ViewTicket} />
<Route path="/viewTicket/:id/edit" exact component={EditTicket} />
</Switch>
</LayoutWrapper>
</div>
</BrowserRouter>
</Provider>
Ticket.js
<Link to="/viewTicket/:id/edit">
<Button size="lg" onClick={this.handleEdit}>
<Pencil />
Edit
</Button>
</Link>
You forgot to include the actual ID in the URL. You're just directing the user to this literal string that has ":id" in it:
<Link to="/viewTicket/:id/edit">
Whatever your ID values is (for demonstration let's assume it's in a variable called id
), you'd use that to build your URL:
<Link to={`/viewTicket/${id}/edit`}>
As an aside, this is a very strange structure and will likely lead to confusion:
<Link to="/viewTicket/:id/edit">
<Button size="lg" onClick={this.handleEdit}>
Putting a button inside of a link means that you're trying to simultaneously do two different things. Should this.handleEdit
be invoked? Or should the user be redirected by the link? It's best to invoke a single operation. If some logic needs to happen inside of this.handleEdit
before redirecting the user, then remove the <Link>
and manually redirect the user (likely using the useHistory
hook) after performing that logic.