Answer the question
In order to leave comments, you need to log in
How to generate a link in React?
Hello!
There is a separate landing page with a promotion - they can get to it from a letter.
In the letter, a link on a button looks like this:
site.com/bonus?offer=1&lang=ua&country=ua
And so, the person went to the landing page - there is a "Next" button and now it should take over the parameters from the current link (from the button)
<code>site.com/signup?offer=1&lang=ua&country=ua</code>
const email = urlQueries['email'];
const phone = urlQueries['phone'];
const date = urlQueries['date'];
const offer = urlQueries['offer'];
const source = urlQueries['source'];
const lang = urlQueries['lang'];
const country = urlQueries['country'];
urlQueries['lang']
gives ua
<a href={location.pathname + lang && `&lang=${lang}`}>
Открыть страницу
</a>
<Link
to={{
pathname: '/signup',
query: {
lang: lang,
source: source,
offer: offer,
country: country,
},
}}
>
Button
</Link>
Answer the question
In order to leave comments, you need to log in
In the end - here is my working solution:
Importing Link and useLocation
import { Link, useLocation } from 'react-router-dom';
const { search } = useLocation();
const params = {
lang: lang,
source: source,
offer: offer,
};
if (search !== '') {
to['search'] = queryString.stringify(params);
} else {
to['search'] = `lang=${lang}`;
}
<Link to={to}>Button</Link>
(Changed answer)
//index.js
import React from "react";
import { render } from "react-dom";
// import react router
import { BrowserRouter, Link } from "react-router-dom";
import toLinkParams from "./toLinkParams";
const params = {
pathname: "/signup",
search: toLinkParams({
lang: "ua",
source: "3",
offer: 1,
country: "ua"
})
};
const App = () => (
<BrowserRouter>
<div className="sans-serif">
<Link to={params}>Button</Link>
</div>
</BrowserRouter>
);
render(<App />, document.getElementById("root"));
//toLinkParams.js
export default function toLinkParams(params) {
return (
"?" +
Object.entries(params)
.map((param) => {
const [key, value] = param;
return `${key}=${value}`;
})
.join("&")
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question