Reputation: 396
I have a component called TableComponent
. I want to redirect path tables/:table
to tables/:table?tab=tab1
and all different tabs use the same TableComponent
.
For example:
tables/:table?tab=tab1
-> TableComponent
tables/:table?tab=tab2
-> TableComponent
tables/:table?tab=tab3
-> TableComponent
I have the code below but it doesn't work:
<Redirect
exact
from="/tables/:table"
to={{
pathname: "/tables/:table",
search: "?tab=tab1"
}}
/>
<Route
path="/tables/:table" <- how can I make this route ignore the query params?
component={TableComponent}
/>
Or should i do the redirect inside the TableComponent
?
Upvotes: 1
Views: 2275
Reputation: 458
Edited:
Add a parent component above the Table Component and check if there are query params in the URL using React Router's useHistory. If there are none, use the useHistory hook and do history.push(tables/:table?tab=tab1).
Original answer:
I don't think you need the redirect. Use the route to take you to the TableComponent.
<Route
path="/tables/:table"
component={TableComponent}
/>
When the user clicks a link that should direct to a certain tab, add the query param to the URL, like so:
<Link to={`tables/${table}?tab=${tab}`}
The URL would be something like tables/august-finances?tab=1
or whatever.
In the tables component, use the useHistory
hook to see if there's a search parameter and what it is. This is a built-in prop of the hook. Anything after the ?
in the URL will be viewable from history.
Ex.
import { useState, useEffect } from 'react;
import { useHistory } from 'react-router;
const TableComponent = () => {
// create state for the tab and set it to null
const [tab, setTab] = useState(null);
let history = useHistory();
useEffect(() => {
// this will be `tab=tab1`
const queryString = history.search;
//isolate the tab by splitting the string by the = character
// it will create array ["tab","tab1"], get the "tab1"
const currentTab = queryString.split("=")[1];
setTab(currentTab);
},[history]);
return(
// if !tab, return nothing
// if tab does have a value, use a conditional expression to return which tab of the table should be shown first
)
}
Upvotes: 1