0

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,

1

2 Answers 2

1

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>
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

External links should be defined as a elements, not Link elements, so that you can use target="_blank" to open the link in a new tab.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.