I have a React, Redux, and Node project that has many internal and external links. I want to make it so that the internal links open in the same page, and the external links open in a new tab. Any help or advice appreciated,
2 Answers
You can create a wrapper component, that decides whether or not the link is external, and renders the <a> element with appropriate props.
Implementing it in that way you'll improve the reusability.
Why the reusability will be improved? Here a few examples:
- Imagine that in the beginning you have 20 external URLs and you manually manage their props (without wrapper component). Later you decide to add a new prop to each one of the external urls and you have to manually change it to 20 places.
- URLs come from an API response and you have to list them in more than one component. Wihout a wrapper component - you will repeat the logic of deciding whether the URL is external or not.
Here is an example with a wrapper component:
// Define the Link wrapper component
class Link extends React.Component{
constructor(props) {
super(props);
this.state = {
target: props.target || this.getTarget(props.href)
};
}
getTarget(url) {
const siteDomain = 'stackoverflow.com';
const isExternal = (url.indexOf(siteDomain) === -1);
if (isExternal) return '_blank';
return '_self';
}
render() {
const props = Object.assign(this.props, ...this.state);
return <a {...props}>{this.props.children}</a>
}
}
// Use the Link wrapper
class Example extends React.Component{
render() {
return <Link href="http://google.com/">This is an external link</Link>
}
}