I have a website built using Docusaurus 2.
I'm wondering if it is possible to add optional parameters to the URL of the site. For example, I may want to have https://www.example.com/docs/introduction?param=abc, then I will use the value of param in my components.
Is it feasible in Docusaurus?
Not sure if I'm understand your question, but I don't see why not. Having query params wouldn't change the URL, you just need to use window.location.search and parse the params, or use React Router's APIs to do it for you.
ReactJS way:
import { useHistory, useLocation } from '#docusaurus/router';
function YourComponent() {
const history = useHistory();
const setSearch = () => {
history.push({
search: `name=${value}`,
});
}
// ...your logic
}
Related
I am using react router v4 to change location in ReactJs.
this.props.history.push("/profile");
<Link to="/profile" />
The above code works fine.
Now I want to keep a param consistent in URL http://localhost:3000?source=test by using the same code as above.
One approach is that I find all the occurrences in the code and add condition that if params source=test exist then append it to the the URL as well but this approach doesn't look fine to me as I have add condition on every redirect, Link and history.push
Second approach that I find is that use of listener on location update given by react router
In my Main Route file
class App extends Component {
componentDidMount() {
this.unlisten = this.props.history.listen((location, action) => {
if (/source=ep/.test(this.props.location.search)) {
location.search = _startsWith(location.search, "?") ? location.search + "&source=test" : "?source=test"
}
});
}
}
With this approach I can easily append the params in search query of react router but the param doesn't show up in URL.
the URL looks like this http://localhost:3000/profile and When I get search params from react-router console.log(this.props.location.search) it shows the param source=test and it's exactly what I want but In this case if user refreshes on this page the search params lost from react-router as well because it's not in the URL.
Can you guys help me to keep source=test consistent even in URL.
I have been trying to figure out to how to capture a coupon code using react-router-dom's URL Parameters. I was hoping to be able to capture a coupon in the URL to set a state.
Example: https://localhost:3000/checkout?coupon=FREE3000&referrer=MATTHEW;
I want to be able to parse the URL to take the parameters Coupon & Referrer to set in the state, and to prefill a form in a checkout page.
Is this possible using React Router Dom? Are there any alternative solutions?
Yes this is possible via react router with a custom hook and the useLocation hook. Anyways you will use URLSearchParams. There is no direct function from react router.
const useQuery = () => new URLSearchParams(useLocation().search)
// use in component
const query = useQuery();
// get desired value with query.get(name)
const coupon = query.get("coupon");
const referrer = query.get("referrer");
Refer to this example from the react router docs
If you want to not use react router simply use the window.location.search property instead of useLocation. See the MDN documentation
The short answer is no, useParams gets the parameters after the base url not the query parameters.
For an answer on how to get the query parameters see this question How to get query parameters in react-router v4
I want to change a URL query for the current page in Next JS without triggering the page change event. My use case is to simply remember the week being viewed in a calendar, similar to Google Calendar. Here's what I've tried:
import Calendar from '../components/Calendar'
import { formatDate } from '../utils'
class CalendarDashboardPage extends React.Component {
refreshQuery(date) {
const { pathname, asPath } = this.props.router
const d = formatDate(date) // YYYY-MM-DD
this.props.router.push(pathname, asPath, { query: { d }, shallow: true })
}
render() {
return <Calendar onDateChange={this.refreshQuery) />
}
}
export default withRouter(CalendarDashboardPage)
This almost seems to work OK, but because this.props.router.push triggers a page change in Next, it causes the page loading bar that I'm using (nprogress) to appear on screen. I've tried this.props.router.push({ query: { d } });, but no luck.
So my question: is there any way to change the router query without triggering events such as routeChangeStart(url)?
You can keep track of the previous pathname and do a conditional check in the routeChangeStart event handler to see if the pathname(without query) changes:
// _app.js
import Router from "next/router";
let previousPathname = null;
function handleRouteChange(url) {
const pathname = url.split('?')[0];
if (previousPathname && previousPathname !== pathname) {
console.log(`App is changing from ${previousPathname} to ${pathname}...`);
}
previousPathname = pathname;
};
Router.events.on("routeChangeStart", handleRouteChange);
...
This may not answer your question directly since it will still trigger Router.events but hopefully can help you with your use case.
Short version: you can't (at least AFAIK).
The first requirement to change the URL in the browser without reload the page is to do that in a single page application.
To achieve I'm afraid you need to drop next/router and start to use react-router, in this article you can find details about how to do a SPA with next using react router.
Once you have done, with this.props.history.push("/new/url") react router feature you can do what you are looking for.
Hope this helps.
My solution was to just use the browser's API.
refreshQuery(date) {
const dateString = formatDate(date) // YYYY-MM-DD
window.history.pushState('', '', `?d=${dateString}`)
}
This changes the date URL parameter when the user flips through the calendar, which can be snagged by componentDidMount() when the users refreshes/shares the URL.
Using vue-router, I have a component check user login status, how can I redirect to the login page URL using the router?
In component, my code:
<script>
export default {
components: {
},
name: 'landing-page',
created: function () {
const router = this.$router
router.go({path: '/login'})
}
}
</script>
But router.go does not work.
Oh, use router.push('/login') can working fine.
Remember that router.go takes a single integer parameter that indicates by how many steps to go forwards or go backwards in the history stack. So to give a path you should use router.push('your_url').
For more information I suggest you read this:
Vuerouter
I am developing a web application where I want to use the URL query for running search queries.
When executing a search, a new request should be sent to the server to get new data, according to the url query params.
Using react-router and Redux, I want to call the dispatch function to fetch the new data from the server according to the query (i.e url change).
I was thinking to use the onChange event and call the dispatch function, like this:
<IndexRoute component={Catalog} onChange={(prevState, nextState, replace) => {dispatch(fetchProducts(nextState.location.search))}}/>
But since my routes is not a React component, I cant access the dispatch function.
I can import my store and use store.dispatch, but I read it is not recommended.
What would you suggest me to do?
To solve this kind of issues, we always declare or routes in a function similar to this:
function createRoutes(store) {
return {
component: App,
childRoutes: [
// Here are defined the other routes.
// They can be defined using plain objects:
{path: "profile", component: Profile},
// Or generated through a function call:
...require("./some/module")(store),
]
}
}
When you do this it is fairly simple to use the store to dispatch an action or to do calculations in React Router lifecycle hooks.
function createRoutes(store) {
return {
component: Settings,
onEnter: (nextState, replace, callback) => {
const state = store.getState()
if (!state.user.logged) {
dispatch(createNotification("You must be logged to perform this"))
replace("/login")
}
callback()
}
}
}