Unable to access Query String parameters inside a React Component - javascript

Here's what I have done so far,
This is the Route that I have defined for a page
<Route path='emails/user/view/:id' component={AccountEmails} />
And here's where the Component is being rendered
const AccountEmails = ({params: {id}}) => <ReceiptsListBox url={"/api/accounts/"+id+"/receipts.json"}></ReceiptsListBox>
Now, within the render() method of the component, I tried to console.log(this.props.location.query) unfortunately this.props.location is undefined.
Here's the YouTube video that I have referred to.
react-router version 2.8.1 and react version 15.3.2

Use this:
const AccountEmails = props => {
const {id} = props.params;
return <ReceiptsListBox
url={"/api/accounts/"+id+"/receipts.json"}
{...props} // =====> notice this part, important
</ReceiptsListBox>
}
Reason is: You are passing only url in props, not all the props values that AccountEmails receives from Routes, because of that location is not available inside ReceiptsListBox component.
Solution is pass all the props that AccountEmails component receive along with one extra url value, by that way location will be available inside ReceiptsListBox component.

Related

React.JS - Passing Data Via Components From Child to Parent

I'm relatively new to React and JavaScript and I'm building a website but I'm having a bit of an issue with passing Data via components from child to parent.
So:
I have my App.js script which is used as a router with react-router-dom, but I would like to store a boolean value using the useState hook. This boolean value that I would like stored should be passed on from a component called Login. I have the script setup to pass that data however the boolean is only stored as long as the Login COmponent page is active and when it is not rendered the boolean store by the useState hook in the App.js script just goes to 'undefined'. I'm assuming that this is happening because the app.js page constantly re-loads and re-renders, so how could I store that value even when the login page is not being rendered?
This is the code setup to pass that data:
app.js
const [authValue, setAuthValue] = useState(false);
const changeValue = (value) => {
setAuthValue(value)
}
And where the Login is called:
<Route path='/signin' element={<Login changeValue={changeValue}value={authValue} />} />
Login.jsx:
const Login = ({changeValue, value}) => {
const [isValid, setIsValid] = useState(true)
changeValue(isValid)
}
The useState hook in React is a solution for component-level state management in functional components.
So, the value of isValid is stored only in Login.js and can be passed as a props to its children components.
Of course, you can also pass some state (or values) from child to parent via functions passed from parent into the child, but this is not the way you should consider if you want to use a state in whole app.
If you need to have the state that should be persistent across the app components, even after one component was unmounted, you should consider global management solutions like React Context API, Redux, MobX or similar libraries.
Try putting the changeValue(isValid) into a useEffect() hook. So:
useEffect(() => {
changeValue(isValid)
}

this.props.match.params.id in React.js is undefined

I want to get the id from the URL therefore I can use this id to get and output the user info but I can't get id from URL. I've seen useParams() but I think it is not applicable with class component. May I know if there is an alternative solution for this?
async componentDidMount(){
const stud_id = this.props.match.params.id;
console.log(stud_id);
}
see error message from console here
The most common way of reading URL params in React is using React Router. In React Router, you get URL params with this.props.match.params like you are trying to, but you have to call your component inside a Route, like for example:
<Route
path="/:id"
component={YourComponent}
/>
instead of just
<YourComponent />
So that your component receives the match prop and can access this.props.match.params.id
If you're using
<Route path="/blah" component={()=><YourComponent someProp={someProp}>}/>
I mean, with arrow function as it child component, you have to pass the pros of the father (Route) to the child (YourComponent) like that:
<Route path="/blah" component={({match})=><YourComponent match={match} someProp={someProp}>}/>
Because you're creating a new "generation" so you have to pass the props by your self

Passing query parameter to props of custom component in NextJS

I'm currently making a profile page wherein the route /profile/displaynamehere will display a page where one of its components is a basic information page that shows the display name of the user.
The component is called BasicInfo and accepts props called displayName. Here's how it looks like:
export default function Profile() {
const router = useRouter();
const displayNameQuery = router.query.displayName;
return (
...
<BasicInfo displayName={displayNameQuery} />
...
)
}
The problem is, displayName or {displayNameQuery} in this context is undefined whenever I try to console.log it. Is there a way wherein I can pass the query parameter as props to my component?

Passing two paramaters in arrow function React Native

I have an arrow function in my react native application.
I am trying to pass first props to be able to navigate between my screens and at the same time I want also to pass in route because I want to pass data between my screens.
However, with the following code I have, whatever I put as the second parameter, it is always undefined... and the first one will work correctly.
Please let me know what I must do to be able to pass in two parameters:
const Home = ({route, props}) => {
{console.log(route.params.id)}
{console.log(props)}
}
I also tried
const Home = ({route}, props) => {
{console.log(route.params.id)}
{console.log(props)}
}
By the way, I am using the latest version of React Native and React Navigation. I'm using purely functional component
Normally, I use to like that
const Home = (props) => {
const {route} = props
{console.log(route.params.id)}
{console.log(props)}
}
Because in component all params are props and only one param is props in component
this not the right way to pass other props. try this.
const Home =({route, ...props}) => {
....
}

Re-render same component on url change in react

I have a route which takes an id and renders the same component for every id, for example :
<Route path='/:code' component={Card}/>
Now the in the Link tag I pass in an id to the component.Now the Card component fetches additional detail based on the id passed. But the problem is it renders only for one id and is not updating if I click back and goto the next id. I searched and found out that componentsWillReceiveProps can be used but during recent versions of React it has been deprecated. So how to do this?
Putting current location as key on component solves problem.
<Route path='/:code' component={(props) => <Card {...props} key={window.location.pathname}/>}/>
I just ran into a similar problem. I think you are conflating updating/rerendering and remounting. This diagram on the react lifecycle methods helped me when I was dealing with it.
If your problem is like mine you have a component like
class Card extend Component {
componentDidMount() {
// call fetch function which probably updates your redux store
}
render () {
return // JSX or child component with {...this.props} used,
// some of which are taken from the store through mapStateToProps
}
}
The first time you hit a url that mounts this component everything works right and then, when you visit another route that uses the same component, nothing changes. That's because the component isn't being remounted, it's just being updated because some props changed, at least this.props.match.params is changing.
But componentDidMount() is not called when the component updates (see link above). So you will not fetch the new data and update your redux store. You should add a componentDidUpdate() function. That way you can call your fetching functions again when the props change, not just when the component is originally mounted.
componentDidUpdate(prevProps) {
if (this.match.params.id !== prevProps.match.params.id) {
// call the fetch function again
}
}
Check the react documentation out for more details.
I actually figured out another way to do this.
We'll start with your example code: <Route path='/:code' component={Card}/>
What you want to do is have <Card> be a wrapper component, functional preferrably (it won't actually need any state I don't think) and render the component that you want to have rendered by passing down your props with {...props}, so that it gets the Router properties, but importantly give it a key prop that will force it to re-render from scratch
So for example, I have something that looks like this:
<Route exact={false} path="/:customerid/:courierid/:serviceid" component={Prices} />
And I wanted my component to rerender when the URL changes, but ONLY when customerid or serviceid change. So I made Prices into a functional component like this:
function Prices (props) {
const matchParams = props.match.params;
const k = `${matchParams.customerid}-${matchParams.serviceid}`;
console.log('render key (functional):');
console.log(k);
return (
<RealPrices {...props} key={k} />
)
}
Notice that my key only takes customerid and serviceid into account - it will rerender when those two change, but it won't re-render when courierid changes (just add that into the key if you want it to). And my RealPrices component gets the benefit of still having all the route props passed down, like history, location, match etc.
If you are looking for a solution using hooks.
If you are fetching data from some API then you can wrap that call inside a useEffect block and pass history.location.pathname as a parameter to useEffect.
Code:
import { useHistory } from "react-router";
const App = () => {
const history = useHistory();
useEffect(() => {
//your api call here
}, [history.location.pathname]);
};
useHistory hook from react-router will give the path name so the useEffect will be called everytime it (url) is changed
as described by #theshubhagrwl but
you can use location.href instead of location.pathname to work in all condition
import { useHistory } from "react-router";
const App = () => {
const history = useHistory();
useEffect(() => {
// do you task here
}, [history.location.href]);
};
You can use use UseLocation() from "react-router-dom"
and then use that object in useEffect dependency array.
import {useLocation} from "react-router-dom";
export default function Card() {
const location = useLocation();
useEffect(()=>{}, [location]);
return(
// your code here
);
}
In React Router v4 Adding a Switch tag after Router fixes the problem

Categories