Can a contentEditable div be given a set height in React.js?

I have a contentEditable div that I want to limit in size. The user should not be able to continue typing once the capacity is reached, and no new lines should be added beyond the fixed height. For example, if the div's height is 600px and the user tries to create new lines by pressing enter repeatedly, after reaching the capacity, no additional lines will be allowed. It's like Google Docs where a new page appears when the end is reached, but in this case, nothing happens once the contentEditable div's limit is reached.

Here is my current code without any overflow since the div has a set capacity:

   <div
        ref={contentEditableRef}
        contentEditable
        className="content-to-print"
        style={{
          padding: "20px",
          color: changeToDarkMode === "true" ? "white" : "black",
          backgroundColor: "none",
          overflow: "hidden",
          fontSize: "16px",
          fontFamily: "Arial, sans-serif",
          textAlign: "left",
          top: "80px",
          outline: "none",
          height: "1020px",
          border:'1px solid black',
        }}
     </div>

Answer №1

In this scenario, imagine a EditableDiv component using a ref to point to the div labeled contentEditable, alongside a useEffect hook managing keydown and paste events.

The function handleKeyDown blocks the addition of new lines when the content height reaches or surpasses the maximum height. Meanwhile, handlePaste deals with pasting content and trims it if it exceeds the set maximum height.

Implementation details:

const EditableDiv = () => {
  const editableDivRef = useRef(null);

  useEffect(() => {

    const handleKeyDown = (event) => {
      if (event.key === 'Enter') {
        const currentHeight = editableDivRef.current.scrollHeight;
        const maxHeight = editableDivRef.current.clientHeight;

        if (currentHeight >= maxHeight) {
          event.preventDefault();
        }
      }
    };


    const handlePaste = (event) => {
      event.preventDefault();
      const text = event.clipboardData.getData('text/plain');
      document.execCommand('insertText', false, text);

      if (editableDivRef.current.scrollHeight > editableDivRef.current.clientHeight) {
        trimContent(editableDivRef.current);
      }
    };


    const trimContent = (div) => {
      while (div.scrollHeight > div.clientHeight && div.innerHTML.length > 0) {
        div.innerHTML = div.innerHTML.slice(0, -1);
      }
    };

    const div = editableDivRef.current;
    div.addEventListener('keydown', handleKeyDown);
    div.addEventListener('paste', handlePaste);

    return () => {
      div.removeEventListener('keydown', handleKeyDown);
      div.removeEventListener('paste', handlePaste);
    };
  }, []);

  return (
    <div
      ref={editableDivRef}
      contentEditable
      className="editable-div"
    ></div>
  );
};

Additionally, include the following CSS styling:

.editable-div {
  width: 100%;
  height: 600px;
  max-height: 600px; /* Fixed height */
  overflow-y: hidden; /* Hide vertical overflow */
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with timing errors in React when making a POST request

My current setup involves a React file connected to an Express/Node backend and SQL database. The backend functionalities are working as expected, with all routes tested and verified using Postman. The application can successfully handle GET, POST, UPDATE, ...

What is the best method for retrieving a specific element nested within another element, employing a for loop and storing it in an array using JavaScript?

In my project, I was tasked with retrieving all the select and input elements that are nested within td elements in a table. My approach involved first fetching all the tds and storing them in an array. Then, I used a for loop to iterate through each td an ...

Organizing various response data in an array-type JavaScript variable

Seeking assistance please.. I have successfully created a function to retrieve all supplier data from the database. However, I now want to create javascript variables in array format to store this information. For example - one array for supplier_id and an ...

The challenges of $location.search().name and base href in application URLs

I am working on an Angular app and my URL appears as http://localhost:8080/personal?name=xyz. To extract the 'xyz' value in JavaScript, I am using $location.search().name. Here is a snippet of my code: app.js app.config(function ($locationProv ...

JavaScript array field for space exploration

I am looking to create a 3x3 grid using JavaScript for a web application. Each field should start with a value of false. However, my code doesn't seem to be functioning correctly and I'm having trouble locating the error. The objective is to ensu ...

Attempting to delete a record in a Node.js Express MongoDB Jade application

I am facing a challenge with my application as I attempt to incorporate a button that can delete an entry containing a date and link. When I trigger the button, I encounter an error message stating: Error 404 not found. The goal is to input the date and li ...

I'm having trouble getting my CSS opacity to smoothly transition back to its original state of .5 using setTimeout(). What could be

I recently started learning JS, Jquery, and CSS. My goal is to create a Simon Says style game. However, when I attempt to animate the computer to automatically light up the correct square, I faced some challenges. To address this issue, I decided to star ...

Encountered an error with useFormState when trying to validate a form

Having some trouble with my web application. I'm working on implementing a validation for the board title to ensure it has at least 3 characters, but running into an issue with the useFormState function below. Error Code This is the code section tha ...

Is there a way to blend together two elements within a Bigcommerce theme seamlessly?

Recently, I have been tasked with customizing a Bigcommerce theme for a client. While I am not very experienced with Bigcommerce and only have basic knowledge of php, I have encountered an interesting challenge with the current theme header setup. The exis ...

Unable to retrieve an image from various sources

My setup includes an Express server with a designated folder for images. app.use(express.static("files")); When attempting to access an image from the "files" folder at localhost:3000/test, everything functions properly. However, when trying to ...

The checkbox appears to have selected values, yet the selected options are not visibly displayed

UPDATE I have been utilizing this specific file in order to dynamically generate a list of tags using the code provided below. import React from "react"; class TagElement extends React.Component{ updateCheck(e){ var v = (e.target. ...

Tips for organizing elements onto separate pages for printing while avoiding overflow onto additional pages

I am encountering an issue while attempting to print tables and an image on separate pages. Every time I print, an additional page spills over into a third page, causing overflow. How can I eliminate this extra space or overflow that results in a third pa ...

Applying the 'overflow: scroll' property creates a scroll bar that remains fixed and cannot be scrolled

Looking to showcase the seating arrangement in a cinema hall. If the seats occupy more than 50% of the page, I want a scroll bar to appear. Attempted using "overflow-scroll" without success. View result image <div class="w-50"> <div ...

Enhance jQuery for a dynamic navigation dropdown with multiple sub-menus

Looking for help with a jQuery script as I am a beginner in using jQuery. jQuery(document).ready(function ($) { $(".sub-menu").hide(); $(".current_page_item .sub-menu").slideDown(200);; $("li.menu-item").click(function () { if ($('.sub-menu&apos ...

Stop the Sidebar from showing up on certain pages with Next.js

Currently, I am facing a small issue with my application. The problem lies in the sidebar that appears on my login.jsx page when I specifically do not want it there. However, I would like it to appear on all other pages except for this one. Is there a cond ...

Issue with Bootstrap Carousel Interval Setting not Functioning as Expected

I recently added Twitter Bootstrap-Carousel to a website with the intention of using it to navigate through different sections of a module. However, I'm encountering an issue where setting the interval to false does not work as expected. When I set an ...

Error: The react.js application is unable to access the property 'classList' of a null object

I've encountered a bug that's been causing me some trouble. Every time I try to run my react application, I keep getting an error message that reads TypeError: Cannot read property 'classList' of null. As someone who is new to react, I& ...

Is there a way to dynamically adjust the font size to perfectly fit the content within a div?

There is a division element containing text: <div style="white-space:nowrap;overflow:none;width:50px;"> With some text in it </div> Is there a way to adjust the font size of the text within the division so that all of the content is display ...

ReactJS encountered an error due to exceeding the maximum update depth when attempting to save data using the localStorage feature

I have a custom component called Home that I want to render in different ways based on its state. Currently, I am attempting to set the state of Home using data stored in localStorage. /* The AuthContext const globalState = { email: null, token: nu ...

Customizing the appearance of the dragged element in jQuery UI

Is there a way to modify the color of a draggable list item after it has been dragged? Any assistance is greatly appreciated. $("#DragWordList li").draggable({helper: 'clone'}); ...