React Router v6 onclick - reactjs

I've asked the same question before but now it's not working with react-router v6.
I've simplified the question to how can I output to console when a <Link /> is clicked?
Link in side menu component
<Link to={"/entity"}>Entity</Link>
The route from the main app.js
<Routes>
<Route path="/entity" element={<Entity />} />
</Routes>
How to perform an action once the link is clicked for a second time (the page is already showing) This example is just outputting to console whenever the <Link> is clicked, but the output only shows the first time it loads (or mounts)
function Entity(props) {
console.log('link clicked');
useEffect(() => {
console.log('link clicked');
});
}

The main change from the previous solution to the new one is that RRDv6 doesn't have a Redirect component and the Link component API changed slightly, the route state is now a first-level prop instead of being nested on the to prop object.
Link
<Link
onClick={() => setLinkKey(uuidV4())}
key={linkKey}
to={"/users"}
state={{ key: linkKey }}
>
Users
</Link>
The components rendered on that route still just look for the key to change when clicking that link again if already on the route.

you can use onClicke like a prop in Link :
<Link to={"/entity"} onClick={()=>{
console.log('link clicked');
useEffect(() => {
console.log('link clicked');
});
}}>Entity</Link>

Related

React Router history on browser's back button

I have a home component with a link which loads a display component and in display component i have the same link which loads the display component again.
if user clicks the link many times in Display Component then there will be a lot of router history.i want that when a user clicks the browser back button it should load the home component not all the previous history.
when i use history.replace("/"); in Display component with onClick event then it works only one time back.but again back is resulting the previous history of Display Component
Routes.js
import Home from "./Components/Home"
import Display from "./Components/Display"
<Router>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/:city">
<Display />
</Route>
</Switch>
</Router>
Home.js
<Link to ={`/${city}`} onClick={()=>{dispatch(fetchWeather(city)); }}>Search</Link>
Display.js
<Link to ={`/${city}`} onClick={()=>{dispatch(fetchWeather(city)); }}>Search</Link>
Depending on the version of react router you are using you can just add the replace prop on your Link component in the Display.js file to not push new states on the history stack and instead update the current one.
<Link replace to ={`/${city}`} onClick={()=>{dispatch(fetchWeather(city)); }}>Search</Link>
If you're on an older version where this isn't supported what you can do is have a click handler do this for you
// Display.js file
function Display(props) {
// whatever code you have for this file
const handleViewCity = useCallback((event, city) => {
// prevent the default redirect from happening, were going to manage that ourselves
event.preventDefault()
dispatch(fetchWeather(city))
props.history.replace(`/${city}`)
}, [props.history, fetchWeather])
return (
// your jsx
// keep the href so you get browser builtin functionality like right click "open in new window"
<a href={`/${city}`} onClick={(e) => handleViewCity(e, city)}>Search</Link>
)
}
export default withRouter(Display)
To visualize what would be happening here think of history as a stack of locations. (this is a simple example - pseudo code)
history.push('/city1') // ['/home', '/city1']
history.push('/city2') // ['/home', '/city1', '/city2']
history.push('/city3') // ['/home', '/city1', '/city2', '/city3']
Pressing the browser back button fires a window popstate event. Pop being the keyword there. When the browser back button is pressed your history then looks like this ['/home', '/city1', '/city2'], which is why you were seeing different cities from the history.
Instead you want to use replace to achieve the desired effect
history.replace('/city1') // ['/home', '/city1']
history.replace('/city2') // ['/home', '/city2']
history.replace('/city3') // ['/home', '/city3']

history.goBack doesnt't work on iOS devices, how to fix that?

I made a go Back button on a page which moves user from current page to a previous one. It works fine on PC and Android devices but it doesn't on iOS. Unfortunatelly I don't have a Mac to take a look at devtools to understand what's happening. Might be someone knows how to fix that? I suspect that the reason might be in useParams and React Router, but I don't know...
GoBack.tsx
interface IGoBackLinkProps {
text: string;
}
const GoBackLink: React.FC<IGoBackLinkProps> = ({ text }) => {
const history = useHistory();
return (
<Link className={styles.link} to='/' onClick={() => history.goBack()}>
{text}
</Link>
);
};
export default GoBackLink;
I use this component in this way:
SomeOtherCOmponent = () => {
const {id} = useParams
...
return (
<GoBackLink text={'Назад'} />
...
)
}
The <Link /> component from react-router-dom, by default, will render an <a> tag and it will use the path from the to prop as the href. So your Link is probably rendering something like this but with an onClick event handler:
<a href="/">
Go Back
<a>
When the user clicks this link, the onClick event is dispatched and then the anchor tag takes you to '/'.
One way to fix this would be to just use a button instead of Link:
<button onClick={() => {history.goBack()}}>
Go Back
</button>
If you must use the Link component or an a tag, e.preventDefault() in your onClick handler may also work.

How to use Route in ReactJS

I need some guidance on the reactjs Routes and how to manifest them properly.
So I have my react directory as below (I will omit unnecessary directories and files)
Routes.js
App.js
src/
ComponentOne.jsx
ComponentTwo.jsx
My curent Routes.js looks like this
import ComponentOne from './src/ComponentOne'
import ComponentTwo from './src/ComponentTwo'
<Route path='/banuka/' exact component={ComponentOne} />
<Route path='/banuka/test' exact component={ComponentTwo} />
And in the ComponentOne.jsx there is a nothing but a button wrapped in a Link of react-router-dom
let valueobject = {<some-key-value-pairs>} // take a note on this line
<Link to={`/banuka/test`}>
<Button variant="dark">
Upload Data
</Button>
</Link>
So when I click on this Button it navigates me two ComponentTwo component.
This is where the problem comes in:
I want to pass the variable valueobject which is an object conains key-value pairs as props from ComponentOne to ComponentTwo
But as you can see, the ComponentTwo is already being rendered in the Routes.js
How can I achieve this?
You can suggest me a better way (even if it means, I have to delete the Routes.js, but it is better if I can keep it as is) to achieve this, so it will look like:
<ComponentTwo values={valueobject}/>
Thank you!
You can send as route state
https://reactrouter.com/web/api/Link/to-object
let valueobject = {<some-key-value-pairs>} // take a note on this line
<Link
to={{
pathname: '/banuka/test',
state: {
...valueobject,
},
}}
>
<Button variant="dark">
Upload Data
</Button>
</Link>

Link changing URL but not the page

I am using Ant design breadcrumbs. I am trying to change the page using link and pushing the URL, I can see the URL change but the page in not changing.
I tried using Link, then creating a function for onClick but everything just change the URL.
Route:
<Route exact path="/assistant/:wId/skill/xyz/:sid" component={ xyz } />
Tried process 1:
<Breadcrumb separator=">">
<Breadcrumb.Item
onClick={this.redirectToParam2}>
{param2}
</Breadcrumb.Item>
</Breadcrumb>
redirectToParam2 = () => {
this.props.history.push(`/assistant/${wId}/skill/xyz/${sId}`);
}
Tried process 2:
<Breadcrumb separator=">">
<Breadcrumb.Item>
<Link to= {`/assistant/${wId}/skill/xyz/${sId}`}>
{param2}
</Link>
</Breadcrumb.Item>
</Breadcrumb>
Even I tried without the Breadcrumbs component but it's still not changing the page.
I want the page to change as soon as the URL changes.
Thank you in advance.
Try this,
import { Link } from "react-router-dom";
<Breadcrumb separator=">">
<Breadcrumb.Item>
<Link to= {`/assistant/${wId}/skill/xyz/${sId}`}>
{param2}
</Link>
</Breadcrumb.Item>
</Breadcrumb>
The problem you are running into, is that with changing the parameters used as props for the xyz component, the component is not replaced but gets new properties. Since nothing changes, i'm assuming you have state that gets filled either in the constructor or ComponentWillMount/ComponentDidMount.
React class components have a lifecycle function for this: componentDidUpdate.
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).
Quote from react docs, See: https://reactjs.org/docs/react-component.html#componentdidupdate
componentDidUpdate(prevProps) {
if ((this.props.params.match.sid !== prevProps.params.match.sid) ||
(this.props.params.match.wid !== prevProps.params.match.wid)) {
this.populateState(this.props.params.match); //fill your state
}
}

Using React Router with different tag

React Router has a Link component with generates an HTML <a> element.
I need to generate an <area href=... >.
How can I do it?
You can have Link as child to your component.
<area>
<Link
to={'/path/to/somehwhere}'}>
Click Me
</Link>
</area>
Or you can specify a onclick event handler on area and use hashHistory or browserHistory from react-router to manually navigate user to desired location.
<area onClick={handleClick}>
// your code here
</area>
and handleClick will have
handleClick = (): void => {
hashHistory.push('/path/to/somehwhere'); // or browserHistory
}
In these both ways you can achieve your desired behavior. You can read more about navigating users programmatically here.
Edit: I forgot to mention that you can also wrap your whole component inside Link.
<Link to='/path/to/somewhere'>
<area />
</Link>

Resources