passing parameter to another component using Link in react - javascript

I know if I need to call another component then we need to pass like <A x={y}/> and we can access props.x inside A.
But here I need to call EditCertificate so I need to pass id to EditCertificate. but I am using Link here. I am not able to pass the id. when I am accesssing it, it is coming undefined.
<Link to={`/${props.certificate.id}/edit` } >Edit</Link>
and I am calling this page like below.
<Route path ="/:id/edit" component={EditCertificate} ></Route>
how can I access :id inside the EditCertificate .when I am accessing it is giving undefined. do I need to pass some other properties.

Since EditCertificate is rendered directly by the route:
<Route path ="/:id/edit" component={EditCertificate} />
the route props are passed to EditCertificate. You just need to access them from props.
const { id } = props.match.params;
if EditCertificate is a class component, then obviously access from this.props.
const { id } = this.props.match.params;

since you're using react-router you can simply import useParams hook and get the id in you EditCertificate component
import { useParams } from 'react-router-dom';
const { id } = useParams(); // add inside your component body

Related

Why isn't this React component updated when dependency changes?

I have this simple React component with a search bar, it gets the input value and navigates to an URL setting the input value as a query param. Once in the component, it gets the 'keyword' from the URL query params and calls an API to get results.
It only works the first time. But if I change the input value it doesn't update the 'keyword' variable value, even though the URL is properly updated.
Why isn't my variable updated?
export default function Resultados () {
let keyword = new URLSearchParams(window.location.search).get('keyword')
const apiKey = '123' ;
useEffect(()=>{
axios
.get(`https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&language=es-ES&query=${keyword}&page=1&include_adult=false
`)
.then(res=>{
console.log(res.data)
})
},[keyword])
return (
<>
<h2>Resultados de {keyword}</h2>
</>
)
}
I've included the keyword variable on the useEffect dependency array, but it seems the variable is not changing.
The dependency array to a useEffect will never cause your component to render. In fact, it's only useful if the component is already rendering, at which point it can skip the effect if nothing has changed. Instead, if you want the component to render, you must set state (either here or in some parent component).
So you either need to write custom code which detects when the url changes, and at that point set state; or you can use an existing routing library such as react-router or react-location, which have already written that code for you. For example, here's how you would do it in react-router:
import { useSearchParams } from 'react-router';
export default function Resultados () {
const [searchParams] = useSearchParams();
const keyword = searchParams.get('keyword');
// rest of your code is the same
}

React router v6 access route params and pass as props

In react router v6, how can I pass route params to a component without the need to use useParams() in the component?
This is what I want to do:
<Route
path='/'
element={ProfileComponent username={'thedefault'}
/>
<Route
exact
path='/u/:username/'
render={(props) =>
<ProfileComponent username={props.match.params.username}/>
}
/>
I don't want to put useParams() in the component because this tightly couples it to the URL. For example, what if I wanted to render another ProfileComponent elsewhere, with a different username to that in the URL. It seems to violate best practice for unit testing unless I can do it like my example.
I don't want to put useParams() in the component because this
tightly couples it to the URL. For example, what if I wanted to render
another ProfileComponent elsewhere, with a different username to that
in the URL. It seems to violate best practice for unit testing unless
I can do it like my example.
Any route using a username route match param would still be accessible via the useParams hook, but I think I understand what you are after. If I understand your question correctly you are asking how to map a route match param to a component prop in a generic way.
For this you can simply use a wrapper component to "sip" the route match param and pass it along to your component on any specific prop.
const ProfileComponentWrapper = () => {
const { username } = useParams();
return <ProfileComponent username={username} />;
};
...
<Route
path='/u/:username/'
element={<ProfileComponentWrapper />}
/>
In the docs, it is clearly specified that it is not possible
Normally in React you'd pass this as a prop: , but you don't control that information because it comes from the
URL.
https://reactrouter.com/docs/en/v6/getting-started/tutorial#reading-url-params
So, you have to use useParams in the component

how to pass a variable to a component from history.replace

how can I access this match.chatroomId in the functional component ??
I use history.replace to redirect to the component
onClick = {() => history.replace(`/chat/${match.chatroomId}`)}
using react hook useParams() This is url - http://localhost:8000/personal/1.
So in this case, use const { id } = useParams()
now, if you do console.log(id) , it will give you the exact id of the url. In this case it will give you 1.
useParams() extracts the id from the url and lets us use it.
Thanks.

Getting Global Access to URL ID Params

How do I get global access to the current URL ID params? I'm having trouble getting access to the current URL ID in a child component in React. The ID is needed in order to query a MongoDB database in my ChecklistTool component.
Normally, I'd pass the props and get access to params that way. However, I'm using Editor.js which is not letting me pass the props as required.
This is my Editor.js component. It has access to params information:
<EditorJs
instanceRef={(instance) => (instanceRef.current = instance)}
placeholder="Start typing what's in your head..."
tools={EDITOR_JS_TOOLS}
enableReInitialize={true}
data={data}
/>
This is my custom Checklist component which is rendered as a block inside of the Editor.js component. I'm unable to pass the URL params to this component:
<ChecklistTool
onDataChange={onDataChange}
readOnly={this.readOnly}
data={this.data}
isAdmin={true}
/>
This is the file where I'm using React Router:
<Router>
<Switch>
<Route exact path="/document/:id" component={DocumentView}/>
</Switch>
</Router>
Any idea how to get access to the current URL params ID in all required files? Thanks!
If you are using a version of React >= 16.8 then you can use hooks.
Instead of using props to pass the value, React-Router provides a hook called useParams which enables you to access the URL params from within any component (as long as it is wrapped inside the router), which makes it essentially global and accessible from any child without passing as props.
This is how you use it:
First you import useParams
import {useParams} from "react-router-dom";
Then call the hook
const params = useParams(); //:id param will be in params.id and so on...
If you have tried this approach and did not work for you, let me know more about the kinds of errors you received, if any, and I will look into them.
React-Router reference for more information about useParams hook.

React extract param from url

I'm using react-router for routing . I've used NavLink and Route components like this:
<NavLink className={classes.navLink}
activeClassName={classes.activeNavLink}
to={`/brokers/${n.id}`}\>
....
<Route exact path="/brokers/:id" component={BrokerDetails} />
Now my question is - how do I use the id parameters passed in inside the BrokerDetails component ? I tried reading it via the props but it doesn't exist .
When using component=..., your component will be passed the route props.
In particular, you'll want to access the match object:
const BrokerDetails = ({match}) => <div>{JSON.stringify(match.params)}</div>;
should show you all the parameters; match.params.id would be the id parameter.
If you try to access props.Id won't work because it isn't in that location.
When you try to access params from an URL, which is passed using 'React-router-dom', then the way to access the props is match.params.id

Categories

Resources