react router 4 query parameters example not working - javascript

problem: trying to implement react router query parameters example on my local environment. code below from their website.
import React from "react";
import { BrowserRouter as Router, Link } from "react-router-dom";
function ParamsExample({ location }) {
let params = new URLSearchParams(location.search);
return (
<Router>
<div>
<p>
React Router does not have any opinions about how your parse URL query
strings. Some applications use simple key=value query strings, but
others embed arrays and objects in the query string. So it's up to you
to parse the search string yourself.
</p>
<p>
In modern browsers that support{" "}
<a href="https://developer.mozilla.org/en-US/docs/Web/API/URL">
the URL API
</a>
, you can instantiate a <code>URLSearchParams</code> object from{" "}
<code>location.search</code> and use that.
</p>
<p>
In{" "}
<a href="https://caniuse.com/#feat=url">
browsers that do not support the URL API (read: IE)
</a>{" "}
you can use a 3rd party library such as{" "}
query-string.
</p>
<div>
<h2>Accounts</h2>
<ul>
<li>
<Link to={{ pathname: "/account", search: "?name=netflix" }}>
Netflix
</Link>
</li>
<li>
<Link to={{ pathname: "/account", search: "?name=zillow-group" }}>
Zillow Group
</Link>
</li>
<li>
<Link to={{ pathname: "/account", search: "?name=yahoo" }}>
Yahoo
</Link>
</li>
<li>
<Link to={{ pathname: "/account", search: "?name=modus-create" }}>
Modus Create
</Link>
</li>
</ul>
<Child name={params.get("name")} />
</div>
</div>
</Router>
);
}
function Child({ name }) {
return (
<div>
{name ? (
<h3>
The <code>name</code> in the query string is "{name}"
</h3>
) : (
<h3>There is no name in the query string</h3>
)}
</div>
);
}
export default ParamsExample;
when rendering i get the following error message TypeError: Cannot read property 'search' of undefined which is pretty straight forward, but when i do location.search in my console i get the following output "?name=zillow-group" with that being said location.search is a valid property but not sure why react is not seeing it.

When you're logging location in the console, you are logging the window.location object. In your component, however, there is a location prop defined that takes precedence. It's not shown explicitly in the react-router example, but they are rendering the ParamsExample component somewhere and passing in the location prop.
You can access the react-router location prop (among others) by either using the withRouter hoc or by using the Route component. Here is an example:
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Link, Route } from "react-router-dom";
function ParamsExample() {
return (
<Router>
<div>
<p>
React Router does not have any opinions about how your parse URL query
strings. Some applications use simple key=value query strings, but
others embed arrays and objects in the query string. So it's up to you
to parse the search string yourself.
</p>
<p>
In modern browsers that support{" "}
<a href="https://developer.mozilla.org/en-US/docs/Web/API/URL">
the URL API
</a>
, you can instantiate a <code>URLSearchParams</code> object from{" "}
<code>location.search</code> and use that.
</p>
<p>
In{" "}
<a href="https://caniuse.com/#feat=url">
browsers that do not support the URL API (read: IE)
</a>{" "}
you can use a 3rd party library such as{" "}
<a href="https://github.com/sindresorhus/query-string">
query-string
</a>
.
</p>
<div>
<h2>Accounts</h2>
<ul>
<li>
<Link to={{ pathname: "/account", search: "?name=netflix" }}>
Netflix
</Link>
</li>
<li>
<Link to={{ pathname: "/account", search: "?name=zillow-group" }}>
Zillow Group
</Link>
</li>
<li>
<Link to={{ pathname: "/account", search: "?name=yahoo" }}>
Yahoo
</Link>
</li>
<li>
<Link to={{ pathname: "/account", search: "?name=modus-create" }}>
Modus Create
</Link>
</li>
</ul>
<Route
render={({ location }) => {
let params = new URLSearchParams(location.search);
return <Child name={params.get("name")} />;
}}
/>
</div>
</div>
</Router>
);
}
function Child({ name }) {
return (
<div>
{name ? (
<h3>
The <code>name</code> in the query string is "{name}"
</h3>
) : (
<h3>There is no name in the query string</h3>
)}
</div>
);
}
function App() {
return <ParamsExample />;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Related

How to use Hyperlink in React Router dom Link [duplicate]

I'm totally new with React and I'm facing off a problem with an external Link. I would like to use it for a redirection to GitHub every time I click on the icon but actually the new window is not showing up instead I have this URL :
http://localhost:3000/https://github.com. I don't why it is not working because with my footer i have almost the same code and it is working well. If you have solutions for that it will be much appreciated ! Thank you very much
Carditem.js
import React from 'react';
import { Link } from 'react-router-dom';
function CardItem(props) {
return (
<>
<li className='cards__item'>
<Link className='cards__item__link' >
<figure className='cards__item__pic-wrap' data-category={props.label}>
<img
className='cards__item__img'
alt='Travel '
src={props.src}
/>
</figure>
<div className='cards__item__info'>
<h5 className='cards__item__text'>{props.text}</h5>
<Link
class='social-icon-card-github'
to={{ pathname: "https://github.com" }}
<i class='fab fa-github' />
</Link>
</div>
</Link>
</li>
</>
);
}
export default CardItem;
Footer.js
import React from 'react';
import './Footer.css';
import { Link } from 'react-router-dom';
function Footer() {
return (
<div className='footer-container'>
<section class='social-media'>
<div class='social-media-wrap'>
<small class='website-rights'>© 2020</small>
<div class='social-icons'>
<Link
class='social-icon-link github'
to={{ pathname: "https://github.com" }}
target='_blank'
aria-label='Github'
>
<i class='fab fa-github' />
</Link>
<Link
class='social-icon-link codepen'
to={{ pathname: "https://codepen.io" }}
target='_blank'
aria-label='Codepen'
>
<i class='fab fa-codepen' />
</Link>
<Link
class='social-icon-link Linkedin'
to={{ pathname: "https://www.linkedin.com" }}
target='_blank'
aria-label='LinkedIn'
>
<i class='fab fa-linkedin' />
</Link>
</div>
</div>
</section>
</div>
);
}
export default Footer;
react-router is used for internal navigation, if you want to navigate outside of your website you should use an a element:
<a
class='social-icon-link github'
href="https://github.com"
target='_blank'
rel="noopener"
aria-label='Github'
>
<i class='fab fa-github' />
</a>
The rel="noopener" is a good security practice: https://mathiasbynens.github.io/rel-noopener/
You cannot call external links with react-router-dom's Link component. Try the following:
Link
You can also open links in a new tab:
Link in new tab
If your URL coming from the API's you can use like that
<Link to={{ pathname:`https://${strFacebook}`}} target="_blank"> Facebook </Link>
Hope you have understood.
The main fact is you need to use tag instead of tag.
Side by side you have to endure that the url must start with "https:" else it will always redirect to localhost:........
for example, if you write Github it will not work. You have to write Gitbuh
the link element is not closed
<Link
class='social-icon-card-github'
to={{ pathname: "https://github.com" }}>
<i class='fab fa-github' />
</Link>

Ho to pass react-router-dom link userid through props?

I have six components which I want to redirect to six different links
import Post from "../post/Post";
import ".//posts.css";
export default function Posts() {
return (
<div className="flex-container">
<Post title="2BHK 2Bath" rent="20000" redirect="1" />
<Post title="3BHK 2Bath" rent="25000" redirect="2" />
<Post title="1BHK 1Bath" rent="14000" redirect="3" />
<Post title="3BHK 3Bath" rent="30000" redirect="4" />
<Post title="2BHK 2Bath" rent="18000" redirect="5" />
<Post title="1BHK 1Bath" rent="10000" redirect="6" />
</div>
);
}
Post.jsx
export default function Post({ title, rent, redirect }) {
return (
<div className="post">
<img
className="postImg"
src="https://www.thespruce.com/thmb/aGEhef5NbpY6R_Fahn5fIW8SAHk=/941x0/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/put-together-a-perfect-guest-room-1976987-hero-223e3e8f697e4b13b62ad4fe898d492d.jpg"
alt=""
/>
<div className="postInfo">
<div className="postCats"></div>
<span className="postTitle">
<Link
to={{ pathname: "/post/{redirect}" }}
className="link"
>
{title}
</Link>
</span>
<hr />
<span className="postDate">Rent: {rent}/-</span>
</div>
</div>
);
}
This does not work, clicking on the first post with redirect: 1 redirects me to this URL http://localhost:3000/post/%7Bredirect%7D
I also tried making it like this from a stackoverflow answer
<Link
to={{ pathname: "/post", state: { redirect } }}
className="link"
>
{title}
</Link>
But this also did not work.
How I can make so that, I can pass the redirect_id through the props of the components.
Example:
When I click on component of <Post title="2BHK 2Bath" rent="20000" redirect="1" /> it should redirect me to http://localhost:3000/post/1
How can I do this?
you can try using template string
<Link to={{ pathname: `/post/${redirect || 0}` }} className="link">
{title}
</Link>

react-router-dom link to another page

Problem:
when clicking the link, the address is parsing the value of the "to" properties of the Link in the react-router-dom, please see the output:
http://localhost:3000/https://xxxxxx.github.io/
import React from 'react';
import { Link } from 'react-router-dom';
const Footer = () => {
return (
<footer className='footer-light bg-light'>
<div
className='text-center p-3'
>
<Link
className='text-decoration-none text-dark'
to='https://xxxxxxx.github.io/'
>
© {new Date().getFullYear()} Copyright
</Link>
</div>
</footer>
);
};
export default Footer;
I want to redirect to another page when clicking the link
You can either pass a string, object, function to the to prop to redirect to a specific URL.
Here's how to do with each of them
String:
<Link to="https://google.com">Click me</Link>
Object:
<Link to={{ pathname: "https://google.com" }} target="_blank">Click me</Link>
Function:
<Link to={location => ({ ...location, pathname: "https://google.com" })} />
Works for both external URLs as well as localhost.
Docs: https://reactrouter.com/web/api/Link
you can try this :
<Link to={{ pathname: "https://xxxxxxx.github.io/" }} target="_parent" rel="noopener noreferer">
© {new Date().getFullYear()} Copyright
</Link>
this will open https://xxxxxxx.github.io/ in the same tab.
or,
<Link to={{ pathname: "https://xxxxxxx.github.io/" }} target="_blank" rel="noopener noreferer">
© {new Date().getFullYear()} Copyright
</Link>
this will https://xxxxxxx.github.io/ in a new tab.

How can I pass values from a functional component through a React Router Link to another functional component?

How can I pass values from my ResultItem.js component, to my Result.js component using React Router's Link component?
ResultItem.js
export default function ResultItem({ result }) {
//desctructure the result elements
const {
title,
type,
id,
publisher,
volume,
issue,
page_number,
year_published,
} = result;
return (
<>
<div className="card grey lighten-4" style={{ padding: '1rem' }}>
<span className="badge green white-text">{type}</span>
<h5>{title}</h5>
<h6>Publisher: {publisher}</h6>
<h6>Volume: {volume}</h6>
<h6>Issue: {issue}</h6>
<h6>Page Number: {page_number}</h6>
<h6>Year Published: {year_published}</h6>
<div>
<Link
to={`/${id}`}
className="waves-effect waves-light btn-small blue"
>
Read More
</Link>
</div>
</div>
</>
);
}
Result.js
export default function Result({ title }) {
return (
<>
<div className="container">
<h5>
More information about that thing you just clicked on will be on this
page.
</h5>
<h1>title = {title}</h1>
</div>
</>
);
}
App.js
<Route path="/:id" component={Result} />
<Link to={{
pathname: `/item/${item.id}`,
state: {id: item.id}
}}>
Later you call: {id.id} in Result
Does it works?

React.js router going to other page renders blank page

First of all, I am using stateless components (functional)
The problem I am running into is this:
When going to another route via Link component I am getting the blank page, and after refreshing the page the component loads.
I have all my routes inside the App.js
<BrowserRouter>
<Switch>
<Route path="/panele" component={Dashboard} />
<Route path="/prisijungimas" component={Login} />
<Route path="/skelbimas/:id">
<HeadLine>
<h1>
SURASK DARBĄ <span>GREIČIAU</span> IR <span>EFEKTYVIAU</span>
</h1>
</HeadLine>
<SingleJobPost />
</Route>
<Route exact path="/" component={AllJobPosts} />
</Switch>
</BrowserRouter>
);
To be honest I am kinda desperate over here. When I don't have the exact attribute on the route component pages are loading - but it is stacking on each other - this is not ok for me.
EDIT:
The Dashboard component:
const Dashboard = props => {
let data = JSON.parse(sessionStorage.getItem("user"));
let history = useHistory();
let { path, url } = useRouteMatch();
let header = new URL(window.location.href).searchParams.get("header");
return (
<>
{data === null ? (
<>{history.push("/prisijungimas")}</>
) : (
<DashboardWrapper>
<Navigation>
<DashboardLogo>
<img src={dashboardLogo} />
<h1>Valdymo panelė</h1>
</DashboardLogo>
<nav>
<ul>
<li>
<Link to="/panele/skelbimuvaldymas?header=Valdykite sukurtus darbo pasiūlymus">
Sukurtų darbo pasiūlymų valdymas
</Link>
</li>
<li>
{" "}
<Link path="/panele/valdymas">Pranešimai</Link>
</li>
<li>
{" "}
<Link path="/panele/valdymas">Pagalbos centras</Link>
</li>
<li>
{" "}
<Link path="/panele/valdymas">Vartotoju valdymas</Link>
</li>
<li>
{" "}
<Link path="/panele/valdymas">Logs</Link>
</li>
<li>
{" "}
<Link path="/panele/valdymas">Mano profilis</Link>
</li>
</ul>
</nav>
</Navigation>
<EditorWindow>
<EditorHeader>
<h1>{header}</h1>
</EditorHeader>
<Editor id="style-1">
<Switch>
<Route path={`${path}/skelbimas`}>
<JobPost />
</Route>
<Route
path={`${path}/skelbimuvaldymas`}
component={ControlJobPost}
/>
</Switch>
</Editor>
</EditorWindow>
</DashboardWrapper>
)}
</>
);
};
I fixed the problem this way:
It works with the functional component as well - I approached it this way:
First of all, make sure to make an if statement to check it the values are loaded if it is not that render empty block otherwise render the actual component with all the data.
{!posts ? (
<></>
) : ( COMPONENT) }
The secound thingy which fixed the problem was - in uedEffect method calling async
function, not doing all the logic inside the method it self.
const fetchData = async () => {
const result = await axios("http://localhost:1337/jobposts?confirmed=true");
setPosts(result.data);
};
useEffect(() => {
fetchData();
}, []);
Make the component stateful and handle the data via state.
const Dashboard = props => {
const [data, setData] = useState();
let history = useHistory();
let { path, url } = useRouteMatch();
useEffect(() => {
let data = JSON.parse(sessionStorage.getItem("user"));
setData(() => {
data
});
}, []);
let header = new URL(window.location.href).searchParams.get("header");
return (
<>
{data === null ? (
<>{history.push("/prisijungimas")}</>
) : (
<DashboardWrapper>
<Navigation>
<DashboardLogo>
<img src={dashboardLogo} />
<h1>Valdymo panelė</h1>
</DashboardLogo>
<nav>
<ul>
<li>
<Link to="/panele/skelbimuvaldymas?header=Valdykite sukurtus darbo pasiūlymus">
Sukurtų darbo pasiūlymų valdymas
</Link>
</li>
<li>
{" "}
<Link path="/panele/valdymas">Pranešimai</Link>
</li>
<li>
{" "}
<Link path="/panele/valdymas">Pagalbos centras</Link>
</li>
<li>
{" "}
<Link path="/panele/valdymas">Vartotoju valdymas</Link>
</li>
<li>
{" "}
<Link path="/panele/valdymas">Logs</Link>
</li>
<li>
{" "}
<Link path="/panele/valdymas">Mano profilis</Link>
</li>
</ul>
</nav>
</Navigation>
<EditorWindow>
<EditorHeader>
<h1>{header}</h1>
</EditorHeader>
<Editor id="style-1">
<Switch>
<Route path={`${path}/skelbimas`}>
<JobPost />
</Route>
<Route
path={`${path}/skelbimuvaldymas`}
component={ControlJobPost}
/>
</Switch>
</Editor>
</EditorWindow>
</DashboardWrapper>
)}
</>
);
};

Categories

Resources