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
Related
I know that you can do navigation.navigate("address", {/* params go here */ to send parameters over to another screen. But then you have to navigate there. Is there a way of sending params over without navigating?
I have a application with multiple screens. And I want to update a useState from another component by updating its params so that a button appears. But I dont want to navigate there, I just want to update it so when the user does go there the button will be there.
Like this:
const currentComponent = (navigation) {
return (
<Button onPress={navigation.updateParams("otherComponent", {shouldShowValue: true})} />
)
}
const otherComponent = (route, navigation) {
const {shouldShowValue} = route.params
const [shouldShow, setShouldShow] = useState(shouldShowValue);
return (
{shouldShow ? <Button> Yayy this button appears now <Button /> : null}
)
}
}
'''
this is just pseudo code and not at all
like the code I have written,
but its just meant as an example to get a
understanding of what I mean.
(updateParams) isnt a function that exists,
but I want something similiar like it.
Is there a way of updating the params in a
component from another component without having
to navigate there? Like with
navigate.navigate("address" {params go here})
but without the navigation part?
You can consider using useContext() hook to execute your functionality.
Using navigation library to pass param without navigating to that page is somehow misusing the navigation function.
With useContext, you can share the state(s) among components. If you want to change the value upon clicking action, you can also pass the useState hook into useContext. Alternatively, you can consider to use redux library to share state.
import { useState, createContext, useContext } from 'react';
const shareContext = createContext(null);
export default function demoUseContext() {
const [isClicked, setClicked] = useState(false);
return (
<shareContext.Provider value={{isClicked, setClicked}}>
<ComponentA />
<ComponentB />
</shareContext.Provider>
)
}
function ComponentA() {
const sharedParam = useContext(shareContext);
return (
<button onClick={() => sharedParam.setClicked(!sharedParam.isClicked)}>
click to change value
</button>
);
}
function ComponentB() {
const sharedParam = useContext(shareContext);
return (
sharedParam.isClicked && <div>it is clicked</div>
)
}
As the example above, the code pass the useState hook from parent component into context, where A is consuming the useState from context to setup isClicked via setClicked, B is consuming the value isClicked from context.
You can also manage to setup context with value not only in a hook, but a param / object / function as a callback.
For more details, please refer to https://reactjs.org/docs/hooks-reference.html#usecontext
There're multiple hooks including useContext fyi
Passing parameters to routes
There are two pieces to this:
Pass params to a route by putting them in an object as a second parameter to the navigation.navigate function: navigation.navigate('RouteName', { /* params go here */ })
Read the params in your screen component: route.params.
We recommend that the params you pass are JSON-serializable. That way, you'll be able to use state persistence and your screen components will have the right contract for implementing deep linking.
I am trying to build an ecommerce website, and I hit a problem I cannot seem to resolve. I am very new to react and JS so have some patience please :)
I declared 4 useStates in my app.js:
const [elementeDinState, setElementeDinState] = useState([]);
const [currentCategorie, setCurrentCategorie] = useState("Acasa");
const [subCategorie, setSubcategorie] = useState([]);
const [cartContents, setCartContents] = useState([]);
const fetchData = useCallback(async () => {
const data = await getCategories();
setElementeDinState(data);
}, []);
useEffect(() => {
fetchData().catch(console.error);
}, [fetchData]);
const changeHeader = (dataFromMenuItem) => {
setCurrentCategorie(dataFromMenuItem);
};
const changeCopiiContent = (data1FromThere) => {
setSubcategorie(data1FromThere);
};
const changeCart = (dataFromCart) => {
setCartContents(dataFromCart);
};
I am passing the functions to change those states to different child components as props. my problem is, when I add items to cart it triggers a re render of my component (products listing component) that should not be affected by cartContents and that resets the state of said component to the initial value that changes the items being shown. does useState hook create a single global state comprised of all those states?
If these useState are defined in the app.js and then passed down, when a child will use them chasing the state will happen in the app.js so all the children of <App /> will be re-rendered.
I guess that your app.js looks similar:
function App() {
const [elementeDinState, setElementeDinState] = useState([]);
// ...and the other hooks and methods
return (
<cartContents setElementDinState={setElementeDinState} />
<ProductList />
)
}
In this case the state is in the component so when <CartContents /> changes it, it will trigger a re-render of the and all its children <ProductList /> included.
To avoid this problem think better when each piece of state needs to be and put the state as near as possibile to that component. For example, if the state of the cart does not influence the Product list. Move the useState in the <Cart /> component.
From what I understand, your problem is that you're simply resetting the cartContents state every time you call the changeCart function, correct?
What you probably want, is to add (or remove ?) the item to the cart, like this?
const changeCart = (dataFromCart) => {
setCartContents(oldContents => [...oldContents, dataFromCart]);
};
Here is a description of useState from the oficial site:
useState is a Hook (...). We call it inside a function component to add some local state to it
So it creates just a local state.
About your problem, We need more information, but I believe that some parent component of that widget is trying to render other component instead of your the component that you wanted (let's call it "ProblemComponent") and rendering you ProblemComponent from scratch again, before you can see it.
it's something like that:
function ParentComponent(props: any) {
const isLoading = useState(false);
// Some logic...
if(isLoading) {
return <LoadingComponent/>;
}
return <ProblemComponent/>;
}
If that doesn't work you can also try to use React.memo() to prevent the ProblemComponent to update when it props change.
well, seems like I wanted to change the way react works so I figured out a work around, based on what you guys told me. I declared the state of the productsComponent in the parent component and adding to cart now doesn't force a refresh of the items being shown. thank you!
I am building a Gatsby app, that's mainly written in React. I have a LoggedIn component where I would grab all books that the user has borrowed and display the status on the website. I use Firebase. I hope that within the LoggedIn component, I can fetch the books. But I am not sure how to wait for the fetch method is done. When I use async/await, it just broke because then my functional component would return a Promise instead of a JSX:ELEMENT type. How can I handle this problem?
import React, { useState } from 'react'
import {fetchUserBook} from "../../firebase/firebaseService"
const LoggedIn = ({user}) => { //if I put async before user,
//my LoggedIn component will return a promise, not a JSX component, which will break my code.
const[books,setBooks] = useState([])
fetchUserRestaurant(user.email).then((info) => setBooks(info))
const renderloggedIn = () =>{
return (
<>
<h1>Welcome, {user.email}.</h1> // I hope that I can pass the "books" props here so that I can render it.
// But usually the return statement is invoked before my fetchUserRestaurant method finishes.
</>
)
}
return(
renderloggedIn()
)
}
export default LoggedIn
``
You just need to put your async fetch function inside a useEffect hook because it will be triggered once the DOM tree is loaded. Just add:
useEffect(()=>{
fetchUserRestaurant(user.email).then((info) => setBooks(info))
}, [])
Adding an empty array (deps), will make it will work as a componentDidMount(), since, in a stateless component like yours, you can't use a componentDidMount() lifecycle, you have to use hooks. This will cause a blink content until your request populates your useState hook and it is displayed. You can add a loader or whatever you like if you want to bypass it anyway.
The rest of the code seems correct.
I'm working with dynamic routing in react.
I'm fetching some data from a third-party API. I have my dynamic route to be something like this
<Route path="/:id" component = {item} />
In the item component, I get the value in params.id and use that id to fetch my data in
componentDidUpdate(){ fetchData(this.props.match.params.id);}
The issue I'm having now is that whenever I try to visit another route of the same format /:id from the Item component, the params changes to the new id passed but still retains the old content for the old id. I believe componentDidmount wasn't called since i'm in that same item component. the component wasn't remounted but just updated. What can I do?
You have to make the api call in componentDidMount as well as in componentDidUpdate with class component. Once you fetch the data, you have to set it in state of the component to visually see it.
componentDidmount() {
fetchData(this.props.match.params.id);
}
componentDidUpdate(prevProps, prevState){
if(prevProps.match.params.id !== this.props.match.params.id) {
fetchData(this.props.match.params.id);
}
}
If you rather use react hooks + functional component, this will be simplified for you. You can use useState to maintain data in the state.
import React, { useEffect } from "react";
const YourComponent = props => {
const { id } = props.match.params;
// This will run every time id changes.
useEffect(() => {
fetchData(id);
}, [id]);
return (
<>
Your api call
</>
);
};
I'm taking my first steps with react-router.
I'm currently using the hashHistory for development purposes and I'm performing 'manual' navigation. That is to say, I'm not using Link and I'm invoking history.push('/some/route'); in order to navigate (in response to plain old clicks on anchor tags).
What I'm noticing is that, even when I'm already on the target route, react-router will re-render the relevant target component every time history.push('/target/route'); is invoked: On every push('/target/route'):
the fragment part of the URL remains #/target/route
the query string part of the URL changes to ?_k=somethingRandom
the target component re-renders
I would like for that re-rendering to not happen - I actually expected history.push to be a no-op when I'm already at the route that I'm attempting to push.
I'm apparently missing something, as this is not what's happening. Funnily enough I'm seeing posts from people who are trying to achieve the behaviour that I'd like to get rid of - they'd like to 'refresh' a route without leaving it, so to speak. Which looks pretty much like the opposite problem :).
Could you enlighten me as to what it is I'm misunderstanding and how I would achieve the desired behaviour? Is this perhaps something that would go away if (when) I switch to browserHistory?
My guess is that your component re-renders because something in your prop changes when you make a router push. I suspect it might be the action or key properties of prop.location. You could always check all the values of prop during each render to see what changes.
You can solve this issue by comparing your old route path with the new one in the shouldComponentUpdate life-cycle method. If it hasn't changed you are on the same route, and you can prevent the re-rendering by returning false. In all other cases, return true. By default this always returns true.
shouldComponentUpdate: function(nextProps, nextState) {
if(this.props.route.path == nextProps.route.path) return false;
return true;
}
You'll have to make further checks as well as this will prevent your component from updating on state updates within the component as well, but I guess this would be your starting point.
Read more about shouldComponentUpdate on the official react docs page.
Use this as an opportunity to return false when you're certain that the transition to the new props and state will not require a component update.
I have the same issue and i find the (dumb) solution.
You just have a <button> (button by default is type=submit) or something similar (form, submit.... etc) thats is reloading the page like a html <form method=GET ...>.
Check it in your code, and remove it.
PD:
_k=somethingRandom > this is just the value inputs (or the button) that you are sending in the form.
I will give this a shot...
If you land here and looking to change your URL (for sharing purposes for example) then RR docs already has the solution described. Just make sure you do not use the history within the component (i.e. this.props.history.push())as you will be (as expected) routed to the target. You are however allowed to access your browser history without any interference with the component's history.
Following tested only on Chrome
// history.js
import { createBrowserHistory } from 'history'
export default createBrowserHistory()
and then from your XYZ component
// XYZ.js
import React from 'react';
import history from './history'
class XYZ extends React.Component {
_handleClick() {
// this should not cause rerender and still have URL change
history.push("/someloc");
}
render() {
return(
<button onClick={this._handleClick.bind(this)}>test </button>
)
}
}
Hope it helps someone else.
In App.js:
shouldComponentUpdate(nextProps, nextState) {
return nextProps.location.search === this.props.location.search
}
I think the easier workaround maybe replacing the Route with our own route
import { Route, withRouter } from "react-router-dom";
function MyRoute({ key, path, exact, component: Component, history }) {
let lastLocation = null;
return (
<Route
key={key}
path={path}
exact={exact}
render={(props) => {
history.listen((location) => {
lastLocation = location;
});
// monkey patching to prevent pushing same url into history stack
const prevHistoryPush = history.push;
history.push = (pathname, state = {}) => {
if (
lastLocation === null ||
pathname !==
lastLocation.pathname + lastLocation.search + lastLocation.hash ||
JSON.stringify(state) !== JSON.stringify(lastLocation.state)
) {
prevHistoryPush(pathname, state);
}
};
return <Component {...props} />;
}}
/>
);
}
export default withRouter(MyRoute);
We use this as a wrapper for actual Route of react-router-dom and it works perfectly for me.
for more please refer here
tsx sample
import {createBrowserHistory} from 'history';
export const history = createBrowserHistory();
ReactDOM.render(
<Router history={history}>
<App/>
</Router>,
document.getElementById("root")
);