Using React Router with different tag - reactjs

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>

Related

React Router v6 onclick

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>

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.

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
}
}

click an image for outside url react.js

I am working on a portfolio and I'm using react.js. I simply want to click an image, for example, a StackOverflow icon, and be able to redirect to the page. I'm seeing all sorts of different ways to go about, yet I cannot get it to redirect.
I am using React-Bootstrap which I don't know if that is going to change anything.
export default class Home extends Component {
render() {
return (
<Grid>
<Jumbotron className="brainImg">
</Jumbotron>
<div class="footer"><center className="iconsBaby">
<Image src="giticon.png" className="githubIcon" to="https://github.com/Joeyryanbridges" />
<Image src="linkedinIcon.png" className="linkedinIcon" href="https://github.com/Joeyryanbridges" />
<Image src="SOFIcon.png" className="githubIcon" href="https://github.com/Joeyryanbridges" />
</center>
</div>
</Grid>
)
}
Thank you for looking.
Generally an Image component should not be a link on its own. What you should do is wrap your image component with an <a> tag or use the Link component if you're using react-router.
<a href="https://github.com/Joeyryanbridges">
<Image src="giticon.png" className="githubIcon" />
</a>
OR with react-router Link
<Link to="https://github.com/Joeyryanbridges">
<Image src="giticon.png" className="githubIcon" />
</Link>
This way the Image component is not concerned with redirects or changing URLs and that functionality is handled by the proper component or tag.
Always keep in mind that separation of concerns is very important when it comes to reusability and maintainability.
Just wrap tag inside an like this:
<a href="abc.com">
<Image src="abc.png" />
</a>
Or If you are using react-router,then you can do this:
import { Link } from "react-router-dom";
<Link to="www.abc.com">
<Image src="abc.png" />
</Link>
Hope this help:
1.You can first declare in the state
load:false
2.use the onClick event and call a function like -
<Image src="giticon.png" className="githubIcon" onClick={()=> handleClick()} />
Inside the function set load to true.
Now check the value of the load to direct to whatever you need.
I hope it works.
There is another method to it , which is just create a onclick attribute to your react element
<img src="<img-link>" alt="<alt-text>" onClick={link} />
and then outside the return statement of your react function you can use 2 methods to link the image which is
location.replace and location.href
both of which would have syntax as follow
window.location.href = "<link>";
and
window.location.replace("<link>");
the methode to use this both is as follow
const link= () => { //remember the onclick attribute mentioned in img tag is having name **link**
window.location.href = "<the-link-to-which-you-want-to-redirect";
}
in this way you can achive your desired output!!
line 6 contain the function and line 18 contain styled react image element... refer if you want
Note:-
window.locatio.replace("")
will replace the webpage , so some one clicking on the image would not be able to use back button of browser .
So use them according to your need!!
The easiest way I've found is to just make sure you add target="_blank" rel="noopener noreferrer" to your tag. Like this:
<a href={ resume } target="_blank" rel="noopener noreferrer">
<img className="resume" src={ resumeLogo } alt="Link to resume" />
</a>
To use an image as a link in React, wrap the image in an tag or a Link tag if using react-router. The image will get rendered instead of the link and clicking on the image will cause the browser to navigate to the specified page.
import {Link} from 'react-router-dom';
The function code can be as follows:
<div>
<Link to="/your-pagename-or-url">
<img src="https://hamedvahedi.com/sample.jpg" alt="" />
</Link>
</div>

How to handle onclicks on hyperlinks most gracefully

What I want is rendered HTML that looks like this My cool Slug.
That means that someone can right-click on the link and open in a new tab. That'll bypass the fancy pushState stuff that react-router provides.
However, if someone makes a regular click, I need to update redux to say what the new slug is (or pagination page or whatever) AND call browserHistory.push(...).
There has to be a simpler way that is convenient. Something that does almost all of this without all the mess. Here's what my application looks like:
// imports
import { browserHistory } from 'react-router'
import changeSlug from './actions'
// the function
makeURL(thing) {
return `/page/${thing.slug}`
}
// this click method
handleClick(event, thing) {
event.preventDefault()
this.props.dispatch(changeSlug(thing.slug))
browserHistory.push(`/page/${thing.slug}`)
}
// the JSX
<a href={makeURL(myobject)}
onClick={(event) => handleClick(event, myobject)}
>Go to {myobject.title}</a>
Also, I tried using event.target in the event handler to get to the a.href attribute but because the <a> tag contains <span> elements, then event.target is the <span> tag I clicked inside the <a> element.
You can use <Link /> from react_router and determine onEnter/etc.
actions in your <Route /> (in <Router />).
Also you can wrap
your <a> in <span> and add some attributes to it and handle
click event.
Also you can add display: block style to <a> => it
shouldn't wraps by <span>

Resources