How can I always get the same part of the URL in react?
example:
http://localhost:3000/supplier/924511e8-9056-4c1e-9976-625bf042924e
I only want "supplier", but this can be anything else. So it's possible for it to be:
http://localhost:3000/product/924511e8-9056-4c1e-9976-625bf042924e
Then I want "product"
But it can also be just http://localhost:3000/supplier/ also in this case I only want the supplier. And this can be anything.
How do I do this? If I've already tried it with pathname.slice(0, pathname.indexOf("/") but this doesn't seem to work.
So I only want the string after the http://localhost:3000/want this/ no matter if there is anything after it or not.
You can use the split method as below:
const url = 'http://localhost:3000/supplier/'
const want_this = url.split('/')[3]
Just use useParams from react router dom
import {useParams} from "react-router-dom";
function Child() {
// We can use the `useParams` hook here to access
// the dynamic pieces of the URL.
let { id } = useParams();
return (
<div>
<h3>ID: {id}</h3>
</div>
);
}
Related
In react-router v5 I was able to use
let keyword = history.location.search
but in react-router v6 I get an error so what is the replacement for that code?
Edit: BTW I am not so good at router and currently converting a code from v5. I was wondering what should keyword return in v5? The path I am currently in?
It's was always the case that you should have accessed the search value from the location object instead of the history object.
See history is mutable
The history object is mutable. Therefore it is recommended to access
the location from the render props of <Route>, not from
history.location. This ensures your assumptions about React are
correct in lifecycle hooks.
If the tutorial is showing using history.location.search I wouldn't give it much weight.
In react-router-dom#6 however, there are no longer any route props, i.e. no history, location, or match props. You instead access these all via React hooks. Note that the history object is also no longer directly exposed out to components, replaced by a navigate function via the useNavigate hook.
To access the queryString RRDv6 introduced a new useSearchParams hook.
Given URL "/somepath?someQueryParam=123"
import { useSearchParams } from 'react-router-dom';
...
const [searchParams, setSearchParams] = useSearchParams();
const someQueryParam = searchParams.get("someQueryParam"); // 123
Additional Question
Edit: Btw I am not so good at router and currently converting a code
from v5 I was wondering what should keyword return in v5 ? The path I
am currently in?
location.search is a string, so you could process the string manually, or create a URLSearchParams object.
Check the RRDv5 Query Parameters demo
They create a custom useQueryHook:
function useQuery() {
const { search } = useLocation();
return React.useMemo(() => new URLSearchParams(search), [search]);
}
then access named query params with the getter:
let query = useQuery();
...
const name = query.get("name");
example url: https://example.com/?foo=bar
import { useSearchParams } from 'react-router-dom'
const Component = () => {
const [searchParams, setSearchParams] = useSearchParams()
const foo = searchParams.get('foo')
console.log(foo) // "bar"
return <></>
}
Obviously, you need to use this inside a router.
Note: all search param values are strings.
i'm totally beginner in react.
I tried to improve my skill day after day.
Today im stuck on problem, i want to create dynamic route with JSON characters (here dragon ball z)
My routes are correct but i want to show biography on only clicked characters like "i click on goku show goku bio"
I want to make it without REACT HOOKS (dont useLocation, useParams ect..).
At moment i'm totally stuck
Can you help me ? how can i do?
Thanks for help :)
here is the blitzstack of my project:
REACT ROUTER DBZ EXERCICE - WITHOUT HOOKS
I don't know why you are using react-router-dom and then not really use it for what it was designed for. You are working with function components, so as far as I can tell, any solution will require a React hook. Whether you just use the useParams hook to get the id to filter by, or if you declare an id state in the parent with useState, or create a React context and use both useState and useContext, or use Redux and useDispatch and useSelector. Do you see where this is headed?
I suggest just using the useParams hook as it's the most trivial to implement.
Fix the character bio route so the id route match param is easier to read and consume.
<Route path="/CharBio/:id" element={<CharBio />} />
With path="/CharBio:id" the link would inject a leading : character into the id with to={`/CharBio${element.id}`}, i.e. instead of "goku" the id param would be ":goku", and this doesn't work easily for filtering.
Fix the link in Perso so it's linking to a "/CharBio/:id" path.
<Link to={`/CharBio/${element.id}`}>
<h1>{element.id}</h1>
</Link>
Use the useParams hook in the CharBio component and filter the API data by id.
export default function CharBio() {
const { id } = useParams();
const element = API.find(el => el.id === id);
return element ? <p>{element.bio}</p> : null;
}
I need to change url completely using following way.
let mycomplteUrl = 'http://localhost/tracks/id/4/39'; // http://localhost/tracks/id/4/39/4 or
props.history.push(`${mycomplteUrl}`);
I'm dynamically creating this mycomplteUrl variable. sometimes variable can be something like
http://localhost/tracks/id/4/39 or http://localhost/tracks/id/4/39/4 or http://localhost/tracks/id/4/39/4/5 (dynamic) or any
it is the same only up to http://localhost/tracks/id/4 this part. I need to replace whole url just like window.location.href = mycomplteUrl in normal javascript, but using props.history.push because i need to avoid from page refresh
Note: for React Router v6
import { useNavigate } from 'react-router-dom';
function MyComponentOrHook() {
const navigate = useNavigate();
// push
navigate(url); // syntax
navigate("/about"); // example
// replace
navigate(url, { replace: true }); // syntax
navigate("/about", { replace: true }); // example
return ... // JSX or hook return values
}
Also, avoid using window.location if you're using React Router, except in rare cases (example - to navigate to an external link).
Reason:
The whole point of using a library React Router is to ease client-side routing so we don't have to do window.location....
window.location causes a reload, which should be avoided in React apps (or any SPA), mostly.
props.history.replace(mycomplteUrl);
If you want to avoid from a page refresh you can do it in this way
window.history.pushState({}, null, "/newPathname");
Try the below way and define the exact URL you want.
window.location.replace(`http://localhost:3000/${dynamic_value}`);
I'm trying to pass parameter inside my URL, but I have a problem with reading. I'm using react-router v4.
URL: http://localhost:3000/reset?token=123
I'm trying to read it this way:
<Route
path="/reset?token=:token"
component={Reset}/>
But this prints empty object console.log(this.props.match.params);. What is strange I have tried to change question mark to other character and looks like it solves my problem, but I would like to keep question mark anyway.
URL: http://localhost:3000/reset_token=123
<Route
path="/reset_token=:token"
component={Reset}/>
This already works console.log(this.props.match.params);. Any idea how to make question mark works also correct? Really important to me is to keep using just react-router without any external libs.
Cheers,
Daniel
How did I solved this issue.
http://localhost:3000?token=mypetismissing
export default function ({ location }) {
const urlParams = new URLSearchParams(location.search);
const token = urlParams.get('token');
console.log(myParams)
return (
<div>
{token}
</div>
)
}
You need query-string
Example:
http://yoursite.com/page?search=hello
const queryString = require('query-string')
class ProductsPage extends React.Component {
componentDidMount() {
let search = queryString.parse(this.props.location.search).search
console.log(search) // ==> hello
}
...
}
Change your path to '/reset'. That'll get the page to render with the token still in the url and you'll be able to grab that token. Happy coding :)
<Route
path="/reset"
component={Reset}/>
Extracting Query Parameters from react router path
URL: http://localhost:3000/reset?token=123
First import useLocation from 'react-router-dom
And do this inside your functional component
const { search } = useLocation();
const parameters = new URLSearchParams(search);
const token = parameters.get('token');
How do I get the params of a route inside a react component
Im using react containers from the react composer package
if this is the whole route
https://learnbuildrepeat-tevinthuku.c9users.io/ReadProjectMeta/wD98XTTtpf8ceyRJT
How do I get only
wD98XTTtpf8ceyRJT
and store its value in a variable inside a react component.
Ive tried to use
FlowRouter.getParam() but it doesnt work. I keep getting undefined
import React from 'react';
export default class ReadProjectMetaLayout extends React.Component {
render() {
var category = FlowRouter.getQueryParam();
console.log(category);
return (
<div>
<h4>Hello World</h4>
</div>
)
}
}
this is the route
FlowRouter.route("/ReadProjectMeta/:_id", {
name: 'project.meta',
action(params) {
mount(ReadProjectMetaLayoutContainer, {
components: (<ReadProjectMeta _id={params._id}/>)
})
}
});
What could be the problem and how do I solve it
To only get the last part of the string:
location.pathname.substr((location.pathname.lastIndexOf('/')+1))
Another pure meteor based thing you can try is from this reference:
FlowRouter.getParam(":_id");
NOTE: Your solution didn't work as you are getting query parameter, query parameters are the parameters that are passed in the url after '?'
i.e. /apps/this-is-my-app?show=yes&color=red
Here in above code color and show are query parameters, while apps is a part of pathname
FlowRouter.getParam(paramName) returns the value of a single URL
parameter
FlowRouter.getQueryParam(paramName) returns the value of a single URL query parameter
Reference:
https://guide.meteor.com/routing.html#accessing-route-info