Codebox sample (add parameter to url manually like https://psolk.csb.app/mytoken): https://codesandbox.io/s/get-params-from-header-psolk
I have following url for my component: http://localhost:3000/CB602FCA-CEA6-41C2-9C70-0F578C92233E
My index.js:
ReactDOM.render(
<BrowserRouter>
<App />
<LoadingIndicator></LoadingIndicator>
</BrowserRouter>
,
document.getElementById("root")
);
This is my router:
const Main = () => (
<div>
<main>
<Switch>
<Route path="/page1/:token?" component={Page1} />
<Route path="/:token?" component={Home} />
</Switch>
</main>
</div>
);
In my home page I can easily get my token:
let { token } = useParams();
In my App Component I have the main content and a menu header:
const App = () => (
<div>
<Header />
<Main />
</div>
);
This is my Header:
const Header = () => {
let { token } = useParams();
console.log(token);
return (<div className="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom box-shadow">
<div className="navbar-left my-0 mr-md-auto">
<img width="200" src={Logo} alt=""/>
</div>
<Nav className="my-2 my-md-0 mr-md-3">
<Link to={"/"+token} className={"p-2 text-dark"}>
Home
</Link>
<Link to={"/page1/"+token} className={"p-2 text-dark"}>
About
</Link>
</Nav>
</div>
)};
The problem is in my header I need to take the token from the url and apply it to the links, so when click a link in the header to token will be persisted between the pages. However the token is null in my Header component, how do I get the token from the url so I can add it to my links?