How can I drag the mouse across multiple inputs or elements with contentEditable to select the text inside?

Viewed 98

When contentEditable is set to true, only the element that is focused can be selected. I'm trying to make cells that function like they do in excel. I'd like to be able to edit the cell on a single click, otherwise I would just set contentEditable with state and select them as regular div elements. I thought about doing something with onMouseOut to change the state to false, but thet doesn't seem to work.

App component:

import { useState, useRef, useEffect } from "react";
import Cell from "./Cell";

export default function App() {
  const testRef = useRef();
  const [st, setSt] = useState(false);

  useEffect(() => {
    if (st) testRef.current.focus();
  }, [st]);

  return (
    <div style={{ display: "flex" }}>
      <Cell tabindex="1" />
      <Cell tabindex="2" />
      <Cell tabindex="3" />
    </div>
  );
}

Cell component:

import "./styles.css";
import { useState, useRef, useEffect } from "react";

export default function Cell() {
  const [editing, setEditing] = useState(true);

  const testRef = useRef();

  const stopEditing = () => setEditing(false);
  const startEditing = () => setEditing(true);
  return (
    <div>
      <div
        ref={testRef}
        contentEditable={editing}
        // onBlur={stopEditing}
        // onMouseUp={stopEditing}
        onMouseOver={startEditing}
        style={{
          display: "flex",
          border: "1px solid #696969",
          width: "100px",
          height: "25px",
          cursor: "cell",
          margin: "2px"
        }}
      ></div>
      <p>{editing.toString()}</p>
    </div>
  );
}

https://codesandbox.io/s/unruffled-rain-i0v40g?file=/src/Cell.js:0-734

1 Answers
<div class = "div1" onmousedown = "selectFunction()"> 

function selectFunction() { 

document.getElementByClassName("div1")[0].style.color = "red"; } 

Maybe something like this? However, this will only work for one of the div's, try applying them to all the div's. This might not work, I'll edit it if it does not. (All this does it highlight the div red, probably won't work if you want to select multiple div's at once)

Related