paint-brush
Building a Post Component with Links, onClick Handling, Text Selection, and Clickability Anywhere.by@lastcallofsummer
243 reads

Building a Post Component with Links, onClick Handling, Text Selection, and Clickability Anywhere.

by Olga StogovaJuly 13th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this article, we will explore how to create a versatile post component in React that supports link navigation and onClick event handling. Additionally, we will ensure the ability to select and copy text within the post without triggering link navigation.
featured image - Building a Post Component with Links, onClick Handling, Text Selection, and Clickability Anywhere.
Olga Stogova HackerNoon profile picture

In this article, we will explore how to create a versatile post component in React that supports link navigation and onClick event handling. Additionally, we will ensure the ability to select and copy text within the post without triggering link navigation.




Demo and Resources

The source code for the component is available on GitHub, and you can find the npm package here. Before we dive into the details, you can check out a live demo of the PostWrapper component in action on CodeSandbox.



Problem Statement №1: Text Selection and Link Navigation Conflict

We encountered a conflict between text selection and link navigation when implementing the post component. By default, when users select text within the post, the browser triggers the link navigation behavior, interfering with the intended text selection functionality.


Solution: Prevent Link Navigation on Text Selection

To address this issue, we integrated the following logic into the PostWrapper component:


const selection = window.getSelection();
const textIsSelected = selection && selection.toString().length > 0;

if (textIsSelected) return;


This code snippet checks if any text is selected within the post. If there is a selection, the link navigation is bypassed, allowing users to freely select and copy the text without triggering unintended navigation.


By incorporating this solution, we provide a seamless experience for users who want to interact with the post content, select the text, and copy it without being redirected to the link target.

Problem Statement №2: Handling Clicks on Links Inside the Post

Another challenge we encountered was handling clicks on links inside the post. We wanted to ensure that when users clicked on a link within the post, the link navigation would proceed as expected, without any interference from the post’s click behavior.


Solution: Enabling Link Navigation for Links Inside the Post

To address this issue, we implemented the following logic in the PostWrapper component:


const postLinkClicked = clickedElement.closest("a") !== null;

if (postLinkClicked) return;


This code snippet checks if the clicked element is an <a> tag or a descendant of an <a> tag. We allow the link navigation to proceed without further processing if it is.


This solution ensures that links inside the post behave as expected, allowing users to navigate to the specified URLs without interference from the post’s click-handling logic.


Problem Statement №3: Handling Clicks on Internal Elements with onClick Handlers

We also encountered the challenge of handling clicks on internal elements within the post that have their own onClick handlers. In this scenario, we wanted to ensure that the onClick handler of the internal element would execute without triggering the link navigation defined by the link prop of the PostWrapper component.

Solution: Preventing Link Navigation and Executing the onClick Handler

To address this issue, we enhanced the click-handling logic in the PostWrapper component as follows:


const isChildClicked = wrapperRef.current?.contains(clickedElement) && Boolean(clickedElement?.onclick);

if (isChildClicked) return;


By incorporating this solution, we check if the clicked element is a descendant of the wrapper element and if it has a non-null onclick property. If both conditions are met, we allow the onClick handler of the internal element to execute without triggering the link navigation.


This enhancement ensures that internal elements with their own onClick handlers can function independently within the PostWrapper component without interfering with the link navigation behavior.


Problem Statement №4: Supporting the Simultaneous Use of Link Navigation and onClick Events

Another requirement we had was the ability to use both link navigation and the simultaneously onClick event for specific use cases. We wanted to allow users to define custom actions, such as analytics events when clicking on the post.

Solution: Enabling the Passing of Analytics Events or Custom Actions through the onClick Handler

To address this requirement, we extended the existing click-handling logic in the PostWrapper component to enable the passing of analytics events or custom actions through the onClick handler. Users can define their desired actions within the onClick function passed to the component.


For example:


<PostWrapper
  className="post-wrapper"
  link="https://example.com"
  target="_blank"
  onClick={(event) => {
    // Custom analytics event
    analytics.track('PostClicked', { postId: postId });

    // Additional custom actions
    // ...
  }}
>
  {/* Post content */}
</PostWrapper>


By utilizing the onClick prop, users can define their own event handlers and trigger custom actions alongside or instead of the link navigation.


This flexibility allows users to seamlessly incorporate their tracking, analytics, or other custom logic within the PostWrapper component.

Usage

The react-clickable-post-wrapper npm package provides a flexible and versatile solution for wrapping post elements within an interactive container. This component allows you to handle clicks on internal elements, navigate to a designated URL when clicking on the wrapper, and support the simultaneous use of link navigation and custom onClick events.Installation

Installation

You can install the package via npm:


npm install react-clickable-post-wrapper

Example Usage

Here’s an example of how you can use the PostWrapper component:


import React from "react";
import PostWrapper from "react-clickable-post-wrapper";

const MyPost = () => {
  const handlePostClick = () => {
    console.log("Post clicked!");
  };

  return (
    <PostWrapper
      className="post-wrapper"
      link="https://example.com"
      target="_blank"
      onClick={handlePostClick}
    >
      {/* Your post content */}
    </PostWrapper>
  );
};


In the example above, the PostWrapper component is used to wrap the post content. Clicking on the wrapper triggers the handlePostClick function, and if the click is not handled or prevented, it navigates to the specified link.


You can customize the className,link, and targertprops according to your needs.


I hope that this article will help you in the development of your components and applications. Feel free to comment if you have any suggestions for improving the component.


Have fun building your components and applications, and happy coding!